I'm using a ServerSocket
and ObjectOuputStream
in Java to transfer some objects for a project of mine from a client to a server. I understand that the ServerSocket
class in Java uses TCP and so no packets should be dropped, but what happens if the client crashes in the middle of streaming an object? Do I need to be handling this myself, or will Java recognize that the object coming through the stream is incomplete?

- 2,652
- 21
- 30
-
If your server reads a client's *InputStream* and the client disappears then you'll get a premature *EOF*, an *IOException* or a hanging connection (I'm not sure which, but you should anticipate either one). Premature *EOF* can only be detected if your client has a means of telling the server *ok, I'm done*. If you ever get an *IOException* while receiving data from a client you should drop the connection and log the error somewhere if it's appropriate. Hanging connections can be handled using timeouts ([there is a nice post about this here at SO](http://stackoverflow.com/q/804951/433835)). – Kohányi Róbert Oct 28 '12 at 14:09
2 Answers
Depending on way the connection is severed, you could get one of several exceptions on the server. Your server may complain with an exception such as Connection reset by peer
. Yes your container can recognize that the connection did not terminate correctly. The exception thrown by your container will indicate this.
Note that there are cases where the client may fully transfer your object but the server may still not get it. A load balancer sitting between the two can sever the connection for unknown reasons. Consider those cases too.

- 11,095
- 2
- 38
- 49
The ServerSocket isn't interrupted. The data being sent to the Socket is interrupted. The ObjectInputStream.readObject() method will either throw an IOException or possibly block forever depending on the failure mode. To avert the latter, set a read timeout on the Socket. Then it will throw a SocketTimeoutException.

- 305,947
- 44
- 307
- 483