dublintech
dublintech

Reputation: 17785

Java Client Socket blocking on BufferedReader?

I am using old school java.net.Socket

My client connects to server and does:

BufferedReader in =
   new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String fromServer = in.readLine();

It hangs at in.readLine().

My server accepts a connection from the client and does:

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.print("Hello client\n");

My expectation would be that as soon as out.print("Hello client\n"); is invoked, the client should stop blocking and continue on.

What are my doing wrong?

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =
   new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
String fromServer = in.readLine();

Upvotes: 3

Views: 1169

Answers (2)

user207421
user207421

Reputation: 310913

You are calling out.print("Hello client\n"), which isn't autoflushed, when you should be calling out.println("Hello client"), which is autoflushed.

Upvotes: 2

Amit Deshpande
Amit Deshpande

Reputation: 19185

I guess you are not calling out.flush(); See PrintWriter.flush

From Javadoc

autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer

So Autoflush will not work for print you will need to call flush() mannually

Upvotes: 3

Related Questions