I just wondering what java does when we call close on the inputStream and outStream associated with a socket. What is the difference from the close call on the socket, i.e Socket.close().
if we just close the io stream on the socket, but not close the socket, can we reopen the io stream on the socket again?
Thanks in advance!
The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.
Yes, closing the input stream closes the socket.
You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.
You never got a null because the peer never closed the connection. That's what 'end of stream' means. It doesn't mean 'no more data for the time being'.
From the java api documentation for Socket:
public void close() throws IOException Closes this socket. Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.
Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.
Closing this socket will also close the socket's InputStream and OutputStream.
If this socket has an associated channel then the channel is closed as well.
Closing the InputStream of the Socket will lead to the closing of the Socket. The same goes for closing the OutputStream of the Socket.
From the java api documentation for Socket#getInputStream()
Closing the returned InputStream will close the associated socket.
Check the API documentation, it is there for a reason.
You should close the outermost output stream you have created from the socket. That will flush it. Closing either the socket or the input stream doesn't do that so it isn't adequate. Having closed that output stream you don't need to do anything else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With