java.net.SocketException: Connection reset

Connect reset by peer

如果一端的Socket被关闭(或主动关闭,或因为异常退出而引起的关闭),另一端仍发送数据,发送的第一个数据包引发该异常(Connect reset by peer)。

/**
 * 服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        Socket socket = serverSocket.accept();
    }
}
/**
 * 客户端
 */
public class Client {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket socket = new Socket("127.0.0.1", 8080);
        OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
        TimeUnit.SECONDS.sleep(3);
        writer.write("客户端发送的消息");
        writer.flush();
    }
}
Connection reset 

一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常(Connection reset),简单的说就是在连接断开后的读和写操作引起的。

/**
 * 服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket socket = serverSocket.accept();
            //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            //writer.write("服务端发送的消息");
            //writer.write("\n");
            //writer.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String clientMsg = reader.readLine();
            System.out.println(clientMsg);
        }
    }
}
/**
 * 客户端
 */
public class Client {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket socket = new Socket("127.0.0.1", 8080);
        //BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //String msg = reader.readLine();
        //System.out.println(msg);

        OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
        writer.write("客户端发送的消息");
        //writer.write("\n"); // 这里没有发送换行符,导致服务端 reader.readLine() 以为还没结束,一直在等待,客户端一关闭服务端就会报异常了
        writer.flush();
    }
}

https://www.cnblogs.com/x_wukong/p/10848481.html

https://www.jb51.net/article/95307.htm

最新回复(0)
/jishuoJnmxBvn6tuh7cwmiwO6nkMq2xRHQbMOXCq0EA_3D_3D8