call the method shutdownOutput()
before/instead of calling close()
on the Socket.
For a TCP socket, any previously written data will be sent followed by TCP's normal connection termination sequence.
The other side should also confirm the termination causing an EOF when trying to read from the socket, now you can close
the socket.
EDIT:
sorry, I was wrong, shutdownOutput()
will not be of much help for this question.
It is useful if you have a reading thread blocked waiting to read data from the socket, and want to close the connection (from another thread. Calling close()
in that situation would cause the reading method to get an IOException
(socket closed).
The solution I found to avoid this exception is:
- call
shutdownOutput()
which will close the transmit half of the connection,
- the other side will get an EOF (actually its read method, assuming there is one blocked),
- the other side should close the socket,
- the reading Thread on this side will leave the blocked read (with an EOF),
- this side can also close the socket.