Java server-client readLine() method

43,545

You shouldn't need to change the format of the data sent by the server, and readLine() should work, but I suspect that the server is not flushing or closing the OutputStream after writing the response which could possibly explain things.
Is the call to readLine() hanging? Are you in control of the server code? If so, can you include it?

Revised classes that work as I believe you expect:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientServerTest2
{

    public static void main(String[] args) throws Exception
    {
        Thread serverThread = new Thread(new Server());
        serverThread.start();
        Thread clientThread = new Thread(new Client());
        clientThread.start();

        serverThread.join();
        clientThread.join();
    }

    private static class Server implements Runnable
    {
        @Override
        public void run()
        {
            ServerSocket serverSocket = null;
            try
            {
                serverSocket = new ServerSocket(1234);

                Socket clientSocket = null;
                clientSocket = serverSocket.accept();
                debug("Connected");

                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                String textFromClient = null;
                String textToClient = null;
                textFromClient = in.readLine(); // read the text from client
                debug("Read '" + textFromClient + "'");
                if ("A".equals(textFromClient))
                {
                    textToClient = "1111";
                }
                else if ("B".equals(textFromClient))
                {
                    textToClient = "2222\r\n3333";
                }

                debug("Writing '" + textToClient + "'");
                out.print(textToClient + "\r\n"); // send the response to client
                out.flush();
                out.close();
                in.close();
                clientSocket.close();
                serverSocket.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        private static void debug(String msg)
        {
            System.out.println("Server: " + msg);
        }
    }

    private static class Client implements Runnable
    {

        @Override
        public void run()
        {
            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()));
                debug("Connected");

                String textToServer;

                textToServer = read.readLine();
                debug("Sending '" + textToServer + "'");
                out.print(textToServer + "\r\n"); // send to server
                out.flush();

                String serverResponse = null;
                while ((serverResponse = in.readLine()) != null)
                    debug(serverResponse); // read from server and print it.

                out.close();
                in.close();
                read.close();
                socket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static void debug(String msg)
    {
        System.out.println("Client: " + msg);
    }
}
Share:
43,545
Joey
Author by

Joey

Updated on March 19, 2020

Comments

  • Joey
    Joey about 4 years

    I have a client class and a server class. If client sends message to server, server will send response back to the client, then client will print all the messages it received.

    For example,

    If Client sends "A" to Server, then Server will send response to client "1111". So I use readLine() in client class to read the message from server, then client print "1111" in the console.

    If Client sends "B" to Server, then Server will send response to client "2222\n 3333". So the expected printing output from client is:

    "2222"

    "3333"

    So the response message from server to client may have 1 line or 2 lines depending on the message it send from client to server.

    My question is that how I can use readLine() to read the message that send from server to client. More specifically, if I use the following codes,

    String messageFromServer;
    while(( messageFromServer = inputStreamFromServer.readLine()) != null) {
        println(messageFromServer);
    }
    

    It will only print the first line, and will not print anything else even if I keep sending message from client to server, because readLine() will stops once it has read the first line.

    update: More specifically, I am looking for some methods in the client class to read message that contains 1 or multiple lines from server at a time. I am wondering if there are any ways to do it in client side if I don't want to change the format of the message that sent from server to client.

    update 2 To make my question more clear, I will put some sample codes in the following:

    This is server:

    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 =null;
    String textToClient =null;
    textFromClient = in.readLine(); // read the text from client
    if( textFromClient.equals("A")){
       textToClient = "1111";
    }else if ( textFromClient.equals("B")){
       textToClient = "2222\r\n3333";
    }
    
    
    out.print(textToClient + "\r\n");  // send the response to client
     out.flush();
     out.close();
     in.close();
     clientSocket.close();
     serverSocket.close();
     }
    }
    

    The client:

    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;
    
        while((textToServer = read.readLine())!=null){
            out.print(textToServer + "\r\n" );  // send to server
            out.flush();
    
            String messageFromServer =null;
            while(( messageFromServer = textToServer=in.readLine()) != null){
                System.out.println(messageFromServer);
            }
        }
        out.close();
        in.close();
        read.close();
        socket.close();
    }
    
    private static void debug(String msg)
    {
        System.out.println("Client: " + msg);
    }
     }