programminglearner programminglearner - 6 months ago 12
Java Question

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.

EJP EJP
Answer

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.

Comments