我正在尝试运行一个示例类,该类使用 Observer
接口(interface)和 Observable
子类来检查来自套接字的输入流何时不同于空字符串。这是代码(Observable
类):
@Override
public void run() {
String input;
while (true) {
try {
input = reader.readLine();
if (input != null) {
setChanged();
notifyObservers(input);
} else
System.out.println("Nothing read from the stream");
} catch (IOException e) {
}
}
}
因此,当条件 input != null
为 true 时,就会调用 update()
方法并将其输出到 stdout
从套接字读取了什么。服务器每秒发送一个字符串,观察者以最大速度检查它(没有任何 sleep()
调用)。那么,从套接字拥有的流中读取数据时,BufferedReader.readLine()
到底做了什么?因为 else
block 永远不会被执行。
最佳答案
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
只有当另一端关闭连接时,您才会得到null
。
如果你想实现一种忙等待策略,你可以使用非阻塞 NIO,但要注意这会 100% 使用一个 CPU。
关于java - Socket 上的 BufferedReader.readLine() 是阻塞操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078437/