BufferedReader readLine() 块 [英] BufferedReader readLine() blocks

查看:36
本文介绍了BufferedReader readLine() 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 readLine() 接收数据时,即使我在消息末尾放了一个 "在发送消息时使用 .flush,读取我的消息的 while 循环仍然阻塞.只有当关闭socket连接时,才离开循环.

When receiving data using readLine(), even though I put a " " at the end of the message using the .flush when sending the message, the while loop that reads my message still blocks. Only when closing the socket connection, it leaves the loop.

这是客户端代码:

bos = new BufferedOutputStream(socket.
            getOutputStream());
bis = new BufferedInputStream(socket.
            getInputStream());
osw = new OutputStreamWriter(bos, "UTF-8");
osw.write(REG_CMD + "
");
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 + "
");
osw.flush();

我的代码在服务器上阻塞了 while 循环.谢谢.

My code blocks at the server while loop. Thanks.

推荐答案

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

The BufferedReader will keep on reading the input until it reaches the end (end of file or stream or source etc). In this case, the 'end' is the closing of the socket. So as long as the Socket connection is open, your loop will run, and the BufferedReader will just wait for more input, looping each time a ' ' is reached.

这篇关于BufferedReader readLine() 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆