I have an application that uses simple sockets to pass some characters between two systems. I have my java application running as a server. I establish a connection fine, and even pass one message. However, after one message has been sent my connection closes.
From what I can tell it appears as if on closing the printWriter
and bufferedReader
the socket itself is being closed?! This is bad, as I have multiple messages to send on the same connection.
printWriter = new PrintWriter(theServer.getClientSocket().getOutputStream());
bufferedReader = new BufferedReader(new InputStreamReader(theServer.getClientSocket().getInputStream()));
printWriter.println("the line");
printWriter.close(); //Closing on these lines?
bufferedReader.close(); //Closing on these lines?
Am I full of it? How do I maintain this connection in Java?
You shouldn't close the writer nor the reader. Just flush the writer to make sure your messages will arrive in time. Closing the socket later on will close the respective streams, so you don't need to close them yourself. Just leave your reader/writer objects to the GC.
As @Eddie said (seconds before me! :)), closing the writer and/or the reader will close the underlying socket streams and the socket itself: However, I believe the socket itself will not be closed.
The close () method of BufferedReader class in Java is used to close the stream and release all the system resources associated with the stream operations.
Closing a stream deallocates any value in it or any resources associated with it. The PrintWriter instance once closed won’t work. Also a PrintWriter instance once closed cannot be closed again.
Yes, closing any Writer/Reader will close all other Writers and Readers that they wrap. Don't close it until you are ready to close the underlying socket.
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