Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does closing the BufferedReader/PrintWriter close the socket connection?

Tags:

java

sockets

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?

like image 261
Alex Avatar asked Jan 27 '09 19:01

Alex


People also ask

Should I close the writer and reader sockets?

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.

What happens when you close the writer and/or the reader?

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.

What is the use of close() method in BufferedReader?

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.

What happens when you close a printwriter instance?

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.


1 Answers

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.

like image 198
Eddie Avatar answered Sep 28 '22 06:09

Eddie