1

In my java code, I send a string through socket to another stream.

Sender code:

OutputStream out = socket.getOutputStream();
String u = new String("something as text");
PrintWriter p = new PrintWriter(out);
p.print(resultMessage);
p.flush();
p.print("\0");
p.flush();

Reciever Code:

String s;
while ((s = br.readLine()) != null  ) {
   System.out.println(s);
 }
System.out.println("DONE");

The problem is that after printing the data it recieved, the while loop does not stop and will be stock in while ((s = br.readLine()) != null ). So It does not print Done

1
  • 1
    This should work. Can you show us the rest of the br code? Commented Nov 21, 2017 at 11:21

1 Answer 1

2

If you don't close the connection, there will not be an end-of-stream and the other side will wait forever (unless a read timeout is configured).

If you've finished sending all the data you need, close the socket. Otherwise the receiving end will wait for any other data you might be sending.

Sending NUL (\0) doesn't do anything special, it definitely won't result in null being read by readLine().

If you want to keep sending data back and forth, with something happening in between, you need to come up with a protocol to use (i.e. what kind of messages are being sent and when), and design your program starting from there.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.