views:

248

answers:

4

Hello,

after my last project I had the problem that the client was expecting an object from the server, but while processing the clients input an exception that forces the server to close the socket for security reasons is caught.

This causes the client to terminate in a very unpleasant way, the way I decided to deal with this was sending the client a Input status message after each recieved input so that he knows if his input was processed properly or if he needs to throw an exception.

So my question:

  • Is there a better/cleaner way to close the socket after an exception is caught??

thanks,

+2  A: 

For things like this:

  1. Make sure to put this socket code within a try/catch block.
  2. Close the socket within a 'finally'. That way you ensure that you cleanly close the socket whether there is an exception or not.
SOA Nerd
Thanks for your answer, I do this already the problem is how to communicate to the client that his object is not coming ?
marco
+1  A: 

If I understand correctly you have already closed the socket from the server side, and you need your client to realize this and handle the error accordingly.

Take a look at the Socket documentation and in particular the setSoTimeout method. For example, if the timeout is set to 5 seconds and the client attempts to read from the server socket and he does not get an answer, then the timeout expires and a java.net.SocketTimeoutException is raised and you can catch it and close the socket.

You could also use a ScheduledExecutorService or a Timer to simulate the timeout.

Lombo
A: 

You really can't since the socket is closed, you could listen on the client for

java.net.SocketException: socket closed 

and then you would know that you lost a connection to the server.

Greg
Incorrect, see my answer. You can't 'listen' for exceptions, and that exception doesn't have that meaning.
EJP
+1  A: 

Incorrect. That exception only occurs when you try to use a socket you have closed yourself.

What the OP should be looking for is EOFException, or IOException: 'connection reset', or a SocketTimeoutException.

EJP
Thanks, learned something new.
Greg