Client loses some lines from TCP socket

My ServerSocket writes the following lines:

 OutputStreamWriter outstream = new OutputStreamWriter(clientSocket.getOutputStream()); BufferedWriter out = new BufferedWriter(outstream); out.write("Hello"); out.newLine(); out.write("People"); out.flush(); 

And my client reads it like this:

 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while(true){ line = in.readLine(); if(line == null){ ClientDialog.gui.log.append("NULL LINE\r\n"); } else{ ClientDialog.gui.log.append(line+"\r\n"); } if(in.readLine() == "SHUTDOWN"){ break; } } 

As you can see, I write โ€œHelloโ€, a new line, and then โ€œPeopleโ€ on the socket, but when I start my client, it only prints โ€œHelloโ€ and null again. I do not see what is wrong?


PROBLEM SOLVED:

I had to add out.newLine() after I wrote "People" to the socket, and I had to do line == "SHUTDOWN" not in.readLine() == "SHUTDOWN" when in.readLine() consumed " People. "

It is also recommended that you use the equals() method in the String class instead of == .

Thanks!

This is for future viewers.

+4
source share
4 answers

You call readLine twice per loop.

 if(in.readLine() == "SHUTDOWN"){ break; } 

The code above uses the string "People"

to fix the change

 if("SHUTDOWN".equals(line){ break; } 

You should also send a new line after sending "People"

+9
source

it

  if(in.readLine() == "SHUTDOWN") { break; } 

Must be:

  if(line == "SHUTDOWN") { break; } 

You call readLine() twice and thereby consume one of your lines

In addition, when comparing String types, you must use the equals() method in the String class:

  if(line != null && line.equals("SHUTDOWN")) { break; } 
+3
source

I'm sure your in.readLine() == "SHUTDOWN" consumes "people" in the stream. Further == will not work either.

+3
source

You need to send another new line after sending people. Your readLine call expects it to process more data.

Try

 out.write("Hello"); out.newLine(); out.write("People") out.newLine(); 
+1
source

Source: https://habr.com/ru/post/1387499/


All Articles