Can someone explain the following behavior in Java sockets:
The general idea is this:
This may be what your code looks like:
Socket socket;
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.close();
Now, let's have a look at the description of getOutputStream() method of Socket.
getOutputStream
public OutputStream getOutputStream() throws IOExceptionReturns an output stream for this socket. If this socket has an associated channel then the resulting output stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the output stream's write operations will throw an
IllegalBlockingModeException.Closing the returned
OutputStreamwill close the associated socket.Returns:
an output stream for writing bytes to this socket.
Throws:
IOException - if an I/O error occurs when creating the output stream or if the socket is not connected.
from the description above, we know closing the returned OutputStream will close the associated socket.
Now, when you close the PrintWriter, it'll close the associated OutputStream which will close the associated socket.
It is probably because calling the close() method of PrintWriter is tracing back through the hierarchy and calling the close() method of the SocketOutputStream as well. As part of the close() method for the SocketOutputStream it also calls the close() method for the Socket as well, which would in term close the SocketInputStream as well. Calling the shutdownOutput() function instead sends any previously written data followed by TCP's normal connection termination sequence. It then disables the output stream.