PrintWriter or any other output stream in Java do not know "\r\n"

25,043

Solution 1

Call flush() after you write from client to server, like so:

out.print(textToServer + "\r\n" );  // send to server
out.flush(); // here, it should get you going.

flush(): Flushes output stream and forces any buffered output bytes to be written out.

Solution 2

On top of VishalD's answer, there's no need to worry about using println() or sending with \r\n because readline() looks for \n anyway. From the API:

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.

Share:
25,043
Joey
Author by

Joey

Updated on July 05, 2022

Comments

  • Joey
    Joey almost 2 years

    I have trouble using PrintWriter or any other output stream to send message between server and client program. It works properly if I use println("abc") to communicate, but it does not work if I use print("abc\r\n"), print("abc\n") or print("abc\r"). What I mean by "it does not work" is that the readLine() will not end because it seems not to see "newline" character and it is still waiting for "\r" or "\n"

    To make it more clear, I will simply put some codes in the following: The client:

    import java.net.*;
    import java.io.*;
    
    public class Server {
      public static void main(String[] args) throws IOException {
    
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(1234);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 1234.");
            System.exit(1);
        }
    
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
        }
        System.out.println("Connected");
    
    
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    
        String textFromClient;
        textFromClient = in.readLine(); // read the text from client
        System.out.println(textFromClient); 
    
    
        String textToClient = "Recieved";
        out.print(textToClient + "\r\n");  // send the response to client
    
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
      }
    }
    

    The Server:

    import java.net.*;
    import java.io.*;
    
    public class Client {
    public static void main(String[] args) throws IOException {
    
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
    
        try {
            socket = new Socket("localhost", 1234);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection");
        }
        System.out.println("Connected");
    
        String textToServer;
    
        textToServer=read.readLine();
        out.print(textToServer + "\r\n" );  // send to server
    
        System.out.println(in.readLine()); // read from server
    
        out.close();
        in.close();
        read.close();
        socket.close();
      }
    }
    

    I want to use print() + "\r\n" instead of println() because the server program I am writing has the requirement that the message sent from server to client needs to contain "\r\n" at the end, eg. "this is the message from server to client\r\n". I think println() is the same as print("\r\n"), So I do not think I should use println() + "\r\n", otherwise it will have 2 newlines. (Although I do not know how the client side will read from server because I am asked to just write server program only. They will write the client side to test my server program.) However, I am supposed to send the messages contain "\r\n" at the end but the readLine() seems not recognize it. So what could I do with it?

    If you do not understand my question, you can try the codes above and you will know what I mean.