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

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

问题描述

使用readLine()接收数据时,即使我在发送消息时使用.flush在消息
的末尾添加了\ n,但读取我的消息的while循环仍会阻塞。
只有在关闭套接字连接时才会离开循环。

When receiving data using readLine(), even though I put a "\n" 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 + "\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();

我的代码在循环时阻塞服务器。
谢谢。

My code blocks at the server while loop. Thanks.

推荐答案

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

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 '\n' is reached.

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

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