BufferedReader readLine() 块

2022-09-03 17:17:45

使用readLine()接收数据时,即使我在发送消息时使用.flush在消息末尾放置了一个“\n”,读取消息的while循环仍然阻塞。只有在关闭套接字连接时,它才会离开环路。

下面是客户端代码:

bos = new BufferedOutputStream(socket.
            getOutputStream());
bis = new BufferedInputStream(socket.
            getInputStream());
osw = new OutputStreamWriter(bos, "UTF-8");
osw.write(REG_CMD + "\n");
osw.flush();

isr = new InputStreamReader(bis, "UTF-8");
BufferedReader br = new BufferedReader(isr);

String response = "";
String line;

while((line = br.readLine()) != null){
   response += line;
}

和服务器的代码:

BufferedInputStream is;
BufferedOutputStream os;

is = new BufferedInputStream(connection.getInputStream());
os = new BufferedOutputStream(connection.getOutputStream());

isr = new InputStreamReader(is);

String query= "";
String line;

while((line = br.readLine()) != null){
   query+= line;
}

String response = executeMyQuery(query);
osw = new OutputStreamWriter(os, "UTF-8");

osw.write(returnCode + "\n");
osw.flush();

循环时在服务器上的代码块。谢谢。


答案 1

BufferedReader将继续读取输入,直到它到达末尾(文件或流或源等的末尾)。在这种情况下,“结束”是套接字的关闭。因此,只要套接字连接处于打开状态,您的循环就会运行,而 BufferedReader 将只等待更多输入,每次到达 '\n' 时都会循环。


答案 2

我尝试了很多解决方案,但唯一没有阻止执行的解决方案如下:

BufferedReader inStream = new BufferedReader(new InputStreamReader(yourInputStream));
String line;
while(inStream.ready() && (line = inStream.readLine()) != null) {
    System.out.println(line);
}

如果下一个调用将阻止执行,则返回 false。inStream.ready()readLine()


推荐