input.read(buffer)
will block until data is received. If the stream is closed, it will return -1
as you are testing for. But, since the stream is still open and is waiting for data to arrive, it'll block.
Since you did update your question, I will update my answer. Closing a stream is not the same as terminating a TCP session.
Closing a stream will put the connection into FIN_WAIT_1
or FIN_WAIT_2
and it needs to finish and reset to be fully closed. You need to tell your server that you're shutting down your client and then shut down, or tell the client you're shutting down the server, and then close. Basically, both sides need to close when they wish to terminate the connection. Closing also may, depending on your environment, not even do anything but release references.
In most implementations of low level socket APIs, you have socket_shutdown(2)
which actually sends the FIN
TCP packet for a mutual shutdown initiation.
Basically both parties need to close, or the connection will be stuck in a waiting state. This is a defined behavior in various RFCs. An explanation can be found here.
From the post I linked, you can review the diagram here.