6

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.

Jonas Bräuer
  • 183
  • 2
  • 15
  • 1
    isConnected() does not return false if the peer has disconnected. You have to catch and handle EOFException. – user207421 Feb 21 '13 at 11:58
  • Yes you are right.At `catch(...){}` i have to catch a bunch of exceptions.The `EOFException` catch will invoke a `forceDisconnect()` to close the resources on client side and also adjust the GUI elements for the user. – Jonas Bräuer Feb 21 '13 at 12:16

1 Answers1

2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93