Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly close a socket after an exception is caught?

Tags:

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?
like image 375
woolagaroo Avatar asked Feb 08 '10 12:02

woolagaroo


2 Answers

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.

like image 95
Lombo Avatar answered Oct 11 '22 13:10

Lombo


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.
like image 44
SOA Nerd Avatar answered Oct 11 '22 13:10

SOA Nerd