SocketException: Connection reset on server with ObjectInputStream

前端 未结 2 479
萌比男神i
萌比男神i 2021-01-24 19:15

I\'m trying to get my head around the ObjectInputStream/ObjectOutputStream, so I create a very simple server-client application where the client sends a HashMap object

2条回答
  •  情话喂你
    2021-01-24 19:56

    This happen because the client socket is automatically terminated after that all its code is executed.

    For example, if you add

    while (true) {
        System.out.println("no operation");
        try {
            Thread.sleep(10000);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
    

    at the end of your client code, you don't get any Connection Reset, because your client socket will never be terminated.

    So, the client side socket is closed and the server side socket has to handle this exception. You should just go out from the loop when you get this exception, so:

    boolean connected = true;
    while (connected) {
        try {
            //your code
        } catch (SocketException e) {
            connected = false;
        }
    }
    

提交回复
热议问题