我正在开发一个使用套接字的程序,目前我的代码中有一个函数每秒检查一次来自客户端的心跳。
private void userLoop() { // checks for incoming data from client
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
try {
socketIn.read(); // check for heartbeat from client
String userInput;
while ((userInput = br.readLine()) != null) {
}
} catch (Exception e) {
ControlPanel.model.removeElement(getUsername());
ControlPanel.append(getUsername() + " has disconnected.");
}
}
}, 1000);
}
当客户端通过 X 按钮关闭游戏、关闭他们的计算机、注销时,无论是什么,我都会收到消息“‘用户名’已断开连接”。这正是我想要的,但是,它只适用于代码中的 while 循环。 while 循环基本上什么都不做,我不知道为什么它不能使用 out。
如果我删除 while 循环并使用我的客户端断开连接,则服务器端不会打印任何内容。
String userInput;
while ((userInput = br.readLine()) != null) {
}
上面基本上是无用的代码,但没有它我的程序就不能正常工作..
为什么需要代码,我怎样才能删除它并仍然使我的程序正常工作?
最佳答案
在这种情况下,您的 while 循环实质上是在停止您的程序,直到您不再收到输入字符串。这不是死代码;这只是您安装等待的方式。
否则,根据我在 Timer class 中的理解,它只等待一秒钟,这对于您正在等待捕获的内容来说可能太短了。
关于java - 没有额外的 readLine() 循环就无法检测到断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21173801/