Reputation: 6355
As the title says - if I want to close a socket connection is it enough if I just call mySocket.close()
? What will happen on the other side?
Or, if it's not the way to go, what is? Do I have to send some kind of "finish" message through the socket so the other side knows it should end as well?
Bonus question: java documentations says
Closing this socket will also close the socket's InputStream and OutputStream.
So is closing the socket alone enough or do I have to explicitly close the streams as well (assuming I'm not using try-with-resources
, of course)?
Upvotes: 2
Views: 12584
Reputation: 41958
socket.close()
is a clean way to close the connection. It causes a TCP FIN packet to be sent to the peer and starts the normal TCP shutdown sequence.
It also closes the socket's InputStream
and OutputStream
, I don't see any ambiguity in the documentation on that point.
Upvotes: 1
Reputation: 348
Closing the socket won't do any thing on the other side. The remote host will not know that the connection has been closed.
The only way to check whether the connection is closed is to try to read or write from/to the input/output stream. If -1
is returned by the InputStream#read()
method, then the second side knows that the first side closed the connection. A thrown IOException
also indicates a closed connection.
Normally you don't need to close the in/output stream as they are closed when invoking Socket#close()
. Socket#close()
is the only thing you need to do to close a connection.
But if you have a wrapper stream (e.g. BufferdInputStream
/BufferedOutputStream
) you should explicitly close these wrapper streams to release resources used by these wrapper streams (e.g. byte buffer array). You only need to close the top level wrapper stream as closing the wrapper closes the wrapped stream which closes the wrapped stream of the wrapped stream, too. And so on...
Upvotes: 5