Cannot send full string when using escape character

Here is a simple TCPServer implementation where all I wanted to do was send a string to the client on request.

import java.util.*;
import java.io.*;
import java.net.*;
class TCPServer{
    public static void main(String args[]) throws Exception{
    ServerSocket server = new ServerSocket(4888);
    while(true){
        Socket client = server.accept();
        DataOutputStream out = new DataOutputStream(client.getOutputStream());
        String send = "Bhushan Patil \n 11-237 \n CMPN";
        out.writeBytes(send);
        }
    }
}

But on the clinic side only Bhushan Patil is shown not the rest of the line.

Here is the client code.

import java.util.*;
import java.io.*;
import java.net.*;
class TCPClient{
    public static void main(String args[]) throws Exception{
    Socket client = new Socket("localhost",4888);
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream    ()));
    String display = in.readLine();
    System.out.println(display);
}
}

Can anyone explain why this is happening? When i do

System.out.println(send);

I get the whole line with \ n, so I assume you will not get new lines. Correct me if I am wrong. Thanx

+3
source share
3 answers

readLinereads all incoming input data terminated by a newline. Therefore, you need to continuously read client input in a loop.

while ((display = in.readLine()) != null) {
    System.out.println(display);
}

, Oracle Sample Server

client.close();
+1

, :

 String  display = null  
 while ((display = in.readLine()) != null)
  {
       System.out.println(display );
  }  
+2

Because it in.readLine()reads only the first line.
you do not read the rest of the line. To read the entire line, you need to loop the buffer. Your exit to System.out.println (send)

Bhushan Patil 
 11-237 
 CMPN  

Which contain a new line character that splits your line into multiple lines and a .readLine()function that is read only one line at a time.

You can use . read (char [] cbuf, int off, int len) for reading text.
For instance:

char[] cbuf = new char[1024];
while (in.read(cbuf, 0, cbuf.length) != null) {
      String str =  new String(cbuf);  
      System.out.print(str);
}
0
source

All Articles