Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - readObject() and setSoTimeout()

So, i wrote a thread on my client side , which tries to readObject() 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 isConnected is set to false.

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

@Override
public void run()
{
  this.connection = this.connectionHandler.getSocket();
  while(connectionHandler.isConnected())
  {
    this.readCircle();
  }
  this.connectionHandler.setReadTaskRunning(false);
}

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

}

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

My question now:

In case, if the readObject() 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 readObject() 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.

like image 935
Jonas Bräuer Avatar asked Feb 21 '13 10:02

Jonas Bräuer


1 Answers

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.

like image 161
Audrius Meškauskas Avatar answered Oct 05 '22 03:10

Audrius Meškauskas