需求:客户端将图片上传至服务器端,服务器端接收并保存图片,然后给客户端一个回应。
可能同时有多个客户端向服务器端上传图片,所以就要处理同时多个客户端的并发请求。
思路:只要将服务器端处理客户端的请求放到一个单独的线程中去,就可以处理多任务请求。
客户端
package com.bxd.network;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class PicClent {
public static void main(String[] args) {
try {
Socket s = new Socket("192.168.1.11", 10008);
FileInputStream fis = new FileInputStream("C:\\Users\\Lee64\\OneDrive\\图片\\bizhi.jpg");
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
// 告诉服务端数据已写完
s.shutdownOutput();
InputStream is = s.getInputStream();
byte[] bufIn = new byte[1024];
int num = is.read(bufIn);
System.out.println(new String(bufIn, 0, num));
fis.close();
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端
package com.bxd.network;
import java.net.ServerSocket;
import java.net.Socket;
public class PicServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10008);
while(true) {
Socket s = ss.accept();
new Thread(new PicThread(s)).start();
}
}
class PicThread implements Runnable {
private Socket s;
public PicThread(Socket s) {
super();
this.s = s;
}
@Override
public void run() {
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "......connected");
int count = 1;
try {
InputStream is = s.getInputStream();
File file = new File(ip + ".jpg");
if (file.exists() && file.isFile()) {
file = new File(ip + "(" + count + ")" + ".jpg");
}
while(file.exists() && file.isFile()) {
file = new File(ip + "(" + (count++) + ")" + ".jpg");
}
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
OutputStream os = s.getOutputStream();
os.write("upload success".getBytes());
fos.close();
s.close();
} catch (Exception e) {
throw new RuntimeException(ip + " upload fail");
}
}
}
}