SocketException: Connection reset on server with ObjectInputStream

夙愿已清 提交于 2019-12-02 04:14:18

You're reading the object twice, but only printing the second time. So the client is probably shutdown by the time you try to read the second time, and so the socket has been closed on the remote end, hence exception.

You're reading in an object on the != null check. You don't print it. Then you try to read it again and it bombs.

Once you read from the stream, it's been read. It's a stream, not a buffer. You might want to buffer the read, and then you can inspect that buffer as much as you like.

Simplest example...

Object o = outputStream.readObject();
if(o != null) {
 system.out.println(o);
}
Cristian Traìna

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!