简体   繁体   English

Java TCP 套接字块在 readLine

[英]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() .我正在开发一个 TCP 客户端/服务器应用程序,并面临客户端总是阻塞在br.readLine() I tried to add a \\n , but it did not solve the problem.我试图添加一个\\n ,但它没有解决问题。 Also a char array is blocking, when I only use read instead of readLine.当我只使用 read 而不是 readLine 时,char 数组也会阻塞。

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".那是因为您隐式地使用空行(来自客户端)来表示“消息已完成”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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