2

I tried to read message on socket with bufferreader

My client:

Socket socket = new Socket("10.0.0.4", 12345);

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

System.out.println(in.readLine());

My python server:

(client, (address, _)) = server.accept()  # Accept to new clients (Accept to new command from the phone)
client.send("Hello from server")

But when I send a message from the server to the client, the code gets stack in the last line System.out.println(in.readLine()); like he is waiting for something.

And whan I turn off the server, I get an error.

How can I read the input from my server with Java?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Ziv Sion
  • 165
  • 1
  • 11

1 Answers1

2

As @James comment states, seems like you are waiting for a carriage return or line feed (complete line) that is not being sent by the server.

That leads to your code being waiting forever until \n, \r or \r\n are received.

readLine()

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

So your in.readline() never considers the line to be terminated, and keeps hopefully waiting for it to end. In order to avoid this, instead of sending:

   client.send("Hello from server")

Send

   client.send("Hello from server\n")

Or even better, check if that Python library has something similar to a sendLine() method.


In order to loop receiving server's messages, something like this could work:

while (socket.isConnected()) 
{
  String inputLine;
  while ((inputLine = in.readLine()) != null)
      System.out.println(inputLine);
} 
aran
  • 10,978
  • 5
  • 39
  • 69