事件被转发到客户端套接字,下面的代码正在读取该套接字。大多数情况下,代码会按预期工作。有时,数据包会发送到套接字,这会导致 readline 使用空消息解除阻塞。从那时起,readline 调用再也不会阻塞,从而导致 CPU 峰值。我已经用代码验证套接字没有关闭,输入流没有关闭,isSocketClosed 和 isInputShutdown 都返回 false。 ready 调用只是尝试查看发生了什么,read 调用始终返回 -1。套接字仍在接受数据,新的有效数据包进来,正确处理,但 readline 再也不会阻塞。知道为什么 readline 会这样吗?
while (!this.isInterrupted())
{
String message = null;
do {
message = reader.readLine();
if ( message != null && message.length() > 0 ) {
//if ( log().isDebugEnabled())
log().info( "Got a message, raw data: " + message );
createEvent( message );
}
} while ( message != null && !this.isInterrupted());
if(!reader.ready()) {
log().info("Bytes read: " + reader.read());
Thread.sleep(1000);
}
}
最佳答案
BufferedReader.readLine() 在另一端关闭连接时返回 null
。
如果它不这样做,那么您的 JVM 有一个特别错误的问题。我会确保你有最新的更新。
I have verified with code that the socket is not closed, the input stream has not been shutdown, isSocketClosed and isInputShutdown both return false
这只是意味着您的终端没有close()
流。它不会告诉您有关流另一端的任何信息。
The ready call is just an attempt to see what's happening, the read call always returns -1
这也意味着流结束。
关于java - 套接字读取线不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18619362/