下图描述了服务端在处理客户端请求时可能出现的地方。解决方法是使接收客户端请求和处理请求分离,接收到请求后,新创建线程来处理请求。
package cn.iktz.socket.uploadpic;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
String path = "replace you file path ";
Socket socket = new Socket("192.168.1.108", 8888);
FileInputStream fis = new FileInputStream(new File(path));
OutputStream out = socket.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
fis.close();
socket.close();
}
}
package cn.iktz.socket.uploadpic;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = null;
try {
ss = new ServerSocket(8888);
while (true) {
Socket socket = ss.accept();
new Thread(new UploadHandler(socket)).start();
}
} finally {
ss.close();
}
}
}
package cn.iktz.socket.uploadpic;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class UploadHandler implements Runnable {
private Socket socket;
UploadHandler(Socket socket) {
this.socket = socket;
}
public void run() {
InputStream in = null;
FileOutputStream fos = null;
try {
in = socket.getInputStream();
fos = new FileOutputStream(new File("filePath"));
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}