Search code examples
javasocketsbufferedreader

Read multiple lines using BufferedReader (Socket)


I already read some threads here on stackoverflow, also some tutorials, but I don't find a solution to my problem.

I have Java client which connects to a server, then sends exactly one line to the server, and I get 2 or 3 lines as a response.

Here is my code:

public static void main(String[] args) {
    String message;
    String response;

    try {
        BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
        Socket clientSocket = new Socket(hostname, port);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        message = inFromUser.readLine();
        outToServer.writeBytes(message + '\n');

        // here my program "freezes"
        while ((response = inFromServer.readLine()) != null) {
          System.out.println("response: " + response);
        }
        clientSocket.close();
    } catch (UnknownHostException e) {
        System.out.println("Unknown Host");
    } catch (IOException e) {
        System.out.println("IO Exception");
    }
}

My problem is, I can read every line of the response, but my program won't exit. The line clientSocket.close(); gets never called. What am I doing wrong?


Solution

  • Presumably your server isn't closing the connection - therefore the underlying stream for the reader isn't closed... at any point the server could send more information. readLine() only returns null when the stream has been closed, i.e. there will definitely not be any more data.

    Now we don't know anything about the protocol here, but if the expected behaviour is that the client won't send any more information, and the server will close the connection, then the bug is in the server. If the protocol states that the server will keep the connection open, then the bug is in your client code and you need to work out how to detect the end of data (or send some sort of ack that will cause the server to close the connection, or whatever).