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.

2
  • 1
    isConnected() does not return false if the peer has disconnected. You have to catch and handle EOFException. Commented Feb 21, 2013 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. Commented Feb 21, 2013 at 12:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.