背景
在我用socket进行TCP通信的时候,当我关闭client
端时在服务端出现了Connection reset
的异常。
一、问题
下面是异常信息:
Exception in thread "Thread-12" java.lang.RuntimeException: java.net.SocketException: Connection reset
at com.smile.javabasic.nio.thread.ServerThreadExp.lambda$main$0(ServerThreadExp.java:26)
at java.base/java.lang.Thread.run(Thread.java:842)
Caused by: java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:328)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:355)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:808)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:966)
at java.base/java.io.InputStream.read(InputStream.java:218)
at com.smile.javabasic.nio.thread.ServerThreadExp.lambda$main$0(ServerThreadExp.java:20)
... 1 more
二、问题分分析
通过分析发现,原来是服务器还没有接收完我发送的数据,客户端就被关闭了,我们都知道,进行TCP通信时,连接建立好以后,才会进行数据传输,当数据传输完以后,服务端还会向客户端返回ACK
信息(三次握手),这也可能会导致。下面是我的测试代码。
(1)服务端代码
public class ServerThreadExp {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8088);
while (true){
System.out.println("等待接收");
Socket socket = serverSocket.accept();
new Thread(() -> {
try {
Thread.sleep(5000);
System.out.println("线程:"+Thread.currentThread().getName());
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
in.read(bytes);
System.out.println("数据:"+new String(bytes));
in.close();
socket.close();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
}
}
}
(2)客户端代码
public class ClientThreadExp {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
Socket socket = new Socket("127.0.0.1", 8088);
OutputStream out = socket.getOutputStream();
out.write("hello world".getBytes());
Thread.sleep(1000);
out.close();
socket.close();
}
}
}
三、解决方案
在服务器没有接收完数据之前就把客户端关闭了,这个是自己业务逻辑和操作导致的问题,