一、编写文件上传的客户端
public class FileUploadClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream("D:/Document/Picture/one.jpg");
int len;
byte[] buff = new byte[1024];
while ((len = fis.read(buff)) != -1) {
os.write(buff, 0, len);
}
socket.shutdownOutput();
System.out.println("客户端上传完成!");
InputStream is = socket.getInputStream();
byte[] buff2 = new byte[1024];
int len2 = is.read(buff2);
System.out.println("客户端收到:" + new String(buff2, 0, len2));
is.close();
fis.close();
os.close();
socket.close();
}
}
二、编写线程执行的类
public class FileUploadTask implements Runnable {
private Socket socket;
public FileUploadTask(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
String ip = socket.getInetAddress().getHostAddress();
String fileName = System.currentTimeMillis() + "_" + new Random().nextInt(88888888) + "_" + ip + ".jpg";
FileOutputStream fos = new FileOutputStream("D:/Document/Images/upload/" + fileName);
int len;
byte[] buff = new byte[1024];
while ((len = is.read(buff)) != -1) {
fos.write(buff, 0, len);
}
System.out.println("服务端上传完成!");
OutputStream out = socket.getOutputStream();
out.write("上传完成啦!".getBytes());
out.close();
fos.close();
is.close();
socket.close();
} catch (Exception e) {
System.out.println("文件上传失败!");
}
}
}
三、编写文件上传的服务端
public class FileUploadServer {
public static void main(String[] args) throws IOException {
System.out.println("文件上传服务端启动啦!");
ServerSocket server = new ServerSocket(8888);
while (true) {
Socket socket = server.accept();
FileUploadTask task = new FileUploadTask(socket);
new Thread(task).start();
}
}
}