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!
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.
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.
This is more like a comment than a good answer: (I would rather add a comment to one the answers above but I don't have the rep)
The question, as I read it, is "can I close a stream on a socket and then open a stream on the same socket?"... but people seem to be answering this: "how should I cleanly close my socket?"... which is not the question being asked.
The answer to the question being asked is "no". When you close the stream, you close the socket.
(I do understand why, in at least one case, someone might ask this question. When you are streaming Java Properties over a socket the receiving end has to see EOF to recognize the end of the properties - for the receiver to see EOF the sender has to close the stream/socket. BUT, if you have a command/response protocol operating over that socket, you DON'T want to close it or you'll lose the channel that you want to send a response on. See Java streaming Properties over Socket for one way to handle this)