0

I have the following code on the server side:

InputStream in = socket.getInputStream();
int x;
while(true) {
      x = in.read();
      if(x < 0) break;
      System.out.print((char)x);
}

The client is properly connected and sends some string to the server. But the while loop runs forever. How to detect when the end of the input stream is reached.

1 Answers1

0

Try this:

while((x = in.read()) >= 0) System.out.println((char)x);

in.read() returns the read byte from the stream. If there is no byte to be read, the method will return -1.

Mackiavelli
  • 432
  • 2
  • 12
  • 1
    How is this different to what they already have? And why is `0` not valid? – weston Jul 09 '15 at 13:06
  • this will not work for sockets any better than the original code, this is not an answer –  Jul 09 '15 at 13:11