Dear All,
I have snippet of code as below. It is a listener which is waiting for the data so I use local to telnet to this program in the same machine. Nothing gets printed unless after sending the data I press enter. On the other hand if I use read method it prints it well chracter by chracter.

while ((line = r.readLine()) != null)   {
             // Print the content on the console
              System.out.println (line);
         }

Dani AI

Generated

As pointed out, BufferedReader.readLine() waits for a line terminator from the peer. That is why a telnet session in its usual line mode does not deliver characters to the server until you press Enter. observed that a per-character read loop handled input immediately — that is the right idea when your protocol delivers no newline.

Options and practical fixes (pick one):

  • Make the sender send a terminator (newline or a protocol delimiter). Then readLine() works cleanly.
  • Keep the current sender and switch the server to read raw bytes and parse messages by delimiter (or length prefix). This is efficient and robust.
  • Use a socket timeout (socket.setSoTimeout) or non-blocking NIO so reads don’t block forever while you accumulate a partial message.

Example server-side pattern (read buffers and scan for a delimiter, not the same code already in the thread):

InputStream in = socket.getInputStream();
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
int read;

socket.setSoTimeout(1000); // optional: periodically break out to handle partial data

try {
  while ((read = in.read(buf)) != -1) {
    sb.append(new String(buf, 0, read, StandardCharsets.US_ASCII));
    int idx;
    while ((idx = sb.indexOf("#")) != -1) {       // '#' is the message terminator
      String msg = sb.substring(0, idx);
      sb.delete(0, idx + 1);
      System.out.println(msg);                    // process complete message
    }
  }
} catch (SocketTimeoutException ste) {
  // handle timeout: check sb for partial data or continue waiting
}

Troubleshooting tips:

  • Use printf 'MSG#' | nc localhost 9000 to test sending raw bytes (no telnet line buffering).
  • Log raw byte values (hex) when behavior is surprising — it shows whether a terminator/sentinel actually arrived.
  • Prefer a framing rule (terminator or length) rather than relying on readLine for protocols that don’t use newlines.

Recommended Answers

All 5 Replies

Yes, that's what readLine is. It reads a line, a line being marked by a newline character, which is what you send when you hit enter.

(I presume that r is a BufferedReader - please provide these details next time, so the people who want to help you don't have to make guesses about what they're looking at, and they spend their time solving your problem, not trying to figure out what it is)

Dear Jon,
Sorry below is my full codes. If you notice this part of the code while ((m=r.read()) != -1) I have commented it out it works fine but the problem it process character by character.I just send the same string for the readline it does not work the same where I must press enter. How to achieve the same effect here?

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.IOException;




public class commServer {
  
  
   public static void main(String[] args) {

      try {
			    final ServerSocket serverSocketConn = new ServerSocket(9000);
				
				while (true) 
					{
						try 
						{
					            Socket socketConn1 = serverSocketConn.accept();
                                new Thread(new ConnectionHandler(socketConn1)).start();			            
						}
						catch(Exception e)
						{
							System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
						    e.printStackTrace(System.out);
						}
					}
			
      } 
      catch (Exception e) 
      {
         System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
         e.printStackTrace(System.out);
         //System.exit(0); 
      }
   }
   
}
  class ConnectionHandler implements Runnable {
    private Socket receivedSocketConn1;
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy"); 
    DateFormat inDf=new SimpleDateFormat("ddMMyyHHmmss");  
    DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
  

    ConnectionHandler(Socket receivedSocketConn1) {
      this.receivedSocketConn1=receivedSocketConn1;
    }

 
   //@Override
   public void run() { 
      
      BufferedWriter w = null;
      BufferedReader r = null;
      

      try {
      
         PrintStream out = System.out; 
      	 BufferedWriter fout = null;
         w =  new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
         r = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
         
        
         
         
         int m = 0, count=0;
         String line="";
         String n="";
         w.write("$PA\n");
         w.flush();
         
         
         
         while ((line = r.readLine()) != null)   {
             // Print the content on the console
              System.out.println (line);
         } 
         /*while ((m=r.read()) != -1) 
         {
           	  
           	  
             Date dateIn = new Date();
           	  n = n + (char) m;
           	 
         	  int i = n.indexOf("GET");
						if(i != -1) { 
							break;
						}
			  
         	  if (m==35)
         	  {
	         	  
	             String ori = n;
	             String noCheckSum =  n.substring(0,(n.length()-4));
     			 int addExist = n.indexOf("@");
     			 
                 String[] slave = null;
                 if(addExist!=-1)
                 {
     	            slave = noCheckSum.split("@");
     	          	n = slave[0];
     	         }
			     else
			     {
			     	n = noCheckSum;
			     }
	                     
	             String[] result = n.split(",");
	                            
	             	             
	             w.write("$PA\n");
                 w.flush();
	             int count1 = 0;
			   
			          Date date = Calendar.getInstance().getTime(); 
                      String today = formatter.format(date); 
				      String filename= "MyDataFile"+today+".txt"; 
                      boolean append = true; 
                      
                      FileWriter fw = null;
                      try
                      {
                      
                      fw = new FileWriter(filename,append); 
	                  fw.write(ori+"  "+dateFormat.format(dateIn)+"\n");//appends the string to the file 
	                  Date dateOut = new Date();
	                  fw.write("$PA"+"  "+dateFormat.format(dateOut)+"\n");//appends the string to the file 
                      }
                      catch (IOException ex)  
				      { 
				          //ex.printStackTrace(new PrintWriter(sWriter));
				          System.out.println("MyError:IOException has been caught in in the file operation"+ex.toString());
				          ex.printStackTrace(System.out);
				      } 
      				  finally
      				  {
        
        			   try 
       				   {
        
	                   if ( fw != null ) 
	                   {
	          	       fw.close();
	                   }
	                   else 
	                   {
	        	       System.out.println("MyError:fw is null in finally close");
	                   //logger.log(Level.SEVERE, "MyError:fw is null in finally close", "");
	                   }
       
                       }
				        catch(IOException ex){
				          System.out.println("MyError:IOException has been caught in fw is null in finally close");
				          ex.printStackTrace(System.out);
				
				        }
      				  }
	                  
	             
	             n="";
	            
         	  }
         }*/
      } 
      catch (IOException ex)  
      { 
           System.out.println("MyError:IOException has been caught in in the main first try");
           ex.printStackTrace(System.out);
      }      
      finally
      {
        try 
       	{
        
	        if ( w != null ) 
	        {
	          	w.close();
	        }
	        else 
	        {
	        	System.out.println("MyError:w is null in finally close");
	        }
        }
        catch(IOException ex){
           System.out.println("MyError:IOException has been caught in w in finally close");
           ex.printStackTrace(System.out);
        }
        
      }
   }
}

Dear Jon,
Any comments why is the readline not able to function as the read? Thank you.

Dear Jon,
I notice my line ends with -1 so how to cater that for readline just as I do in read it works fine. Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.