programminglearner
programminglearner

Reputation: 23

Cannot communicate once bufferedwriter is close in java socket programming

I made a server and client Java application. They should communicate each other through TCP sockets with Threads. I used InputStreamReader and BufferedReader to read message, and I used OutputStreamWriter and BufferedWriter to write message. The object of BufferedReader is called reader, and the object of BufferedWriter is called writer.

After playing around with that, I realized the socket becomes irresponsive if the writer is closed.

I closed the writer on server side because it will never send any message, but will read message from client only. it does not throw any exception, but stuck where I called any methods relate to socket such as reader.readline() and socket.setSoTimeout().

The problem was easy to solve since I just don't close the writer. However, I am very curious why the socket is being unable to communicate.

Upvotes: 0

Views: 216

Answers (2)

user207421
user207421

Reputation: 310998

the socket becomes irresponsive if the writer is closed

The socket becomes closed if the writer is closed.

I closed the writer on server side because it will never send any message,

Non sequitur. If you don't need the Writer, don't construct it.

stuck where I called any methods relate to socket such as reader.readline() and socket.setSoTimeout().

It isn't 'stuck'. It's closed. You must have got SocketException: socket closed when you called either of those methods. You should have noticed that, and you should have posted it in your question.

Upvotes: 1

Yogesh Ghimire
Yogesh Ghimire

Reputation: 442

You can make stop it from being irresponsive by trying:

if(reader.ready()){
String result = reader.readline();
}

Upvotes: -1

Related Questions