BufferedReader in Socket Programming

When i am trying to send an input from a client, if i don’t concat "\r\n" at the end of the string, my inputstream waits forever. I have seen various similar posts but couldn’t find a proper solution. My code is as follows:

public void run() {          PrintWriter out = null;     BufferedReader in = null;     try {         out = new PrintWriter(clientSocket.getOutputStream(), true);         in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));          String line;          if (in.ready()) {             if ((line = in.readLine()) != null) {                 System.out.println("Received from client: " + line);                 out.write("Echoing: " + line);                 out.flush();             }         }      } catch (Exception e) {         e.printStackTrace();     } finally {         out.close();         try {             in.close();             clientSocket.close();             System.out.println("Closing connection from " + socketAddress + ", #" + connectionId);         } catch (IOException e) {             e.printStackTrace();         }     } } 
Add Comment
1 Answer(s)

If you only want to read some of the data that was sent, use the read(char[]) method instead of the readLine method. This method returns the number of characters it read as an int. Example:

     char[] buffer = new char[2000];      int read;      if ((read = in.read(buffer)) != -1) {             String line = new String(buffer, 0, read);             System.out.println("Received from client: " + line);             out.write("Echoing: " + line);             out.flush();       } 

What you’ll see happen next is that this code sometimes fails to read the entire message you send from PHP, or that two or more messages are read as one.

If you want to fix that:

This will never work, and it’s not because of PHP or Java. You’re using TCP, a stream oriented protocol. There is no guarantee that the message you write to the socket from the PHP program will arrive in one piece to the receiver. The message may be broken up and you need multiple socket function calls to read it. Or it may go the other direction, and a single call to read returns more than one message.

The solution is to add some kind of framing for the messages so that the receiver knows when it has a complete message. Always ending a message with a line break serves as framing, if messages themselves are single lines. Another solution is to ditch TCP and use a message oriented protocol (like UDP) instead, but that will come with its own complications.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.