Hexa Hexa - 2 years ago 99
Java Question

Java - readObject() and setSoTimeout()

So, i wrote a thread on my client side , which tries to

from a socket stream.

This thread runs as long the client is connected.

The connection to the server can be closed on the client's GUI.
If the client decides to disconnect(this will not exit the client program) by clicking the
"disconnect" menu option, the socket will be closed and a
is set to false.

Since the clients read thread tries to
from stream, while the connection can be closed via the GUI, i set a timeout to 250ms (

public void run()
this.connection = this.connectionHandler.getSocket();

private void readCircle()
this.connectionHandler.readData(); //this uses readObject().
catch(SocketTimeoutException timeout){}


I know that
will block, and to check if the client is still connected, i wraped it in a
, which checks (every timeout) if the client socket is still connected.

My question now:

In case, if the
starts to get a object passed by the server, tries to read it, but while processing a timeout occurs, will the data on the stream be "damaged" in some way, because it canceled.
Or should i just let the
block and catch a exception if the GUI thread wants to close the socket.

I'm not very experienced with sockets and maybe my approach is wrong at all.

h22 h22
Answer Source

Socket read timeout will cause a SocketTimeoutException to be thrown by readObject(). You may not be able to reuse that ObjectInputStream, and the stream may be damaged because its current position will stay largely undefined.

This probably can only be fixed by closing and reopening the connection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download