woolagaroo
woolagaroo

Reputation: 1522

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

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:

Upvotes: 5

Views: 4399

Answers (4)

user207421
user207421

Reputation: 310860

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.

Upvotes: 1

Lombo
Lombo

Reputation: 12235

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.

Upvotes: 2

Greg
Greg

Reputation: 1719

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.

Upvotes: 0

SOA Nerd
SOA Nerd

Reputation: 943

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.

Upvotes: 2

Related Questions