简体   繁体   中英

Java TCP socket blocks at readLine

I'm working on a TCP client/server application and face the issue that the client is always blocking at br.readLine() . I tried to add a \\n , but it did not solve the problem. Also a char array is blocking, when I only use read instead of readLine.

Client:

BufferedReader brInput = new BufferedReader(new InputStreamReader(System.in));
String send = brInput.readLine();

Socket socket = new Socket(host, port);
        
BufferedReader brSend = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pr = new PrintWriter(socket.getOutputStream());
pr.println(send);
pr.flush();
        
System.out.println(brSend.readLine());  // is blocking      

socket.close();

Server:

ServerSocket serverSocket = new ServerSocket(port);
while (true) {
    Socket socket = serverSocket.accept(); // blocks until request is received

    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
        if (line.isEmpty()) break;
    }

    PrintWriter pw = new PrintWriter(socket.getOutputStream());
    pw.write("Hello world\n");
    pw.flush();

    pw.close();
    socket.close();
}

Your code as written does this:

  • The client writes one line, and then tries to read one.

  • The server reads multiple lines until it either gets an empty line, or the end-of-stream. Then it writes a line.

The problem is that server is waiting for the client to do something that it isn't going to do:

  • the client won't send an empty line (unless it read one from standard input),

  • the client won't close the stream ... until it gets the response from the server.

Hence the client is waiting for the server and the server is waiting for the client. Deadlock.


There are various ways to solve this. One simple way would be to change this (in the client)

    println(send);

to this

    println(send); println();

However, the one problem here is that your "protocol" does not cope with the case wants to send an empty line as data. That is because you are implicitly using an empty line (from the client) to mean "message completed".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM