In Java API,
Socket socket = serverSocket.accept(); BufferedReader fromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter toSocket = new PrintWriter(socket.getOutputStream()); //do sth with fromSocket ... and close it fromSocket.close(); //then write to socket again toSocket.print("is socket connection still available?\r\n"); //close socket socket.close();
In the above code, after I close the InputStream fromSocket, it seems that the socket connection is not available anymore--the client wont receive the "is socket connection still available" message. Does that mean that closing the inputstream of a socket also closes the socket itself?
The Close method frees both unmanaged and managed resources associated with the NetworkStream. If the NetworkStream owns the underlying Socket, it is closed as well. If a NetworkStream was associated with a TcpClient, the Close method will close the TCP connection, but not dispose of the associated TcpClient.
close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.
The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more.
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.
Yes, closing the input stream closes the socket. You need to use the shutdownInput method on socket, to close just the input stream:
//do sth with fromSocket ... and close it socket.shutdownInput();
Then, you can still send to the output socket
//then write to socket again toSocket.print("is socket connection still available?\r\n"); //close socket socket.close();
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