Java實現客戶端、服務器文件上傳功能。
1.客戶端的代碼
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("C:\\Users\\cs\\Desktop\\1.jpg");
Socket socket=new Socket("127.0.0.1",8887);
OutputStream os=socket.getOutputStream();
byte[] b=new byte[1024];
int len=0;
while ((len=fis.read(b))!=-1){
os.write(b,0,len);
}
socket.shutdownOutput();
InputStream is=socket.getInputStream();
while ((len=is.read(b))!=-1){
System.out.println(new String(b,0,len));
}
fis.close();
socket.close();
}
}
2.服務器代碼
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(8887);
//讓服務器一直處於監聽狀態(死循環accept方法),有一個客戶上傳文件就保存文件
while (true){
final Socket socket=serverSocket.accept();
//使用多線程提高程序效率,有一個客戶上傳文件就開一個線程,完成文件的上傳
new Thread(new Runnable() {
@Override
public void run() {
try {
File file=new File("C:\\Users\\cs\\Desktop\\downlode");
if (!file.exists()){
file.mkdirs();
}
/*自定義命名規則,防止文件被覆蓋
* */
String filename="itcast"+System.currentTimeMillis()+new Random().nextInt(99999)+".jpg";
FileOutputStream fos=new FileOutputStream(file+"\\"+filename);
InputStream ips= socket.getInputStream();
int len=0;
byte[] bytes=new byte[1024];
while ((len=ips.read(bytes))!=-1){
fos.write(bytes,0,len);
}
OutputStream ops= socket.getOutputStream();
ops.write("上傳成功".getBytes());
fos.close();
socket.close();
}catch (IOException e){
System.out.println(e);
}
}
}).start();
}
}
}