Java &引用;空";当客户端注销聊天程序时无限打印
当两个(或多个)客户端连接到服务器时,当我按其中一个客户端的Java &引用;空";当客户端注销聊天程序时无限打印,java,Java,当两个(或多个)客户端连接到服务器时,当我按其中一个客户端的logout时,他成功断开连接。但是,其他客户端在其文本区域上无限地打印“null”,因此它不停地打印“null” public void run(){ if (socket != null && reader != null) { try { String in; while (keepGoing){
logout
时,他成功断开连接。但是,其他客户端在其文本区域上无限地打印“null”
,因此它不停地打印“null”
public void run(){
if (socket != null && reader != null) {
try {
String in;
while (keepGoing){
try{
in= reader.readLine();
send(in+"\n");
}
}
}
}
}
注意:这不是一个错误,而是一个bug,因此我没有得到任何异常。执行以下操作:
while (messageLoop){
try{
messageInput = reader.readLine();
if(messageInput == null) break;
sendMessage(messageInput+"\n");
}
catch(SocketTimeoutException ste){
Thread.yield();
}
}
这是因为你从读者那里无限地阅读,即使没有什么可读的了。您可以执行以下操作来更正代码:
public void run(){
if (socket != null && reader != null) {
try {
String in;
while (keepGoing){
if(reader != null){
try{
in= reader.readLine();
send(in+"\n");
}
catch(Exception e){
//Exception thrown, do something about it
}
}
else{
// nothing to read, do something else
}
}
}
}
}
听起来像是
reader
连接到传入的套接字流,该套接字流已关闭,因此readLine()返回null,然后在下一行打印出来。一旦返回了
null',就没有必要再次循环调用readLine()
——流的结尾已经遇到了。@AJNeufeld您是说socket!=空
部分?我注释了if
语句(只有条件,而不是全部),我仍然得到了错误。