首页 文章

套接字read()和ready()互锁,客户端断开检测

提问于
浏览
0

好吧,我的问题很简单 . 我试图进行简单的聊天,但我觉得从服务器检测断开的客户端是强制性的 . 当我使用简单时,聊天工作正常(没有这样的检测):

if (this.in.ready())  //preinitialized buffered reader
                    this.dataIn=this.in.readLine();

我浏览过这里发布的很多网站/问题,我读到 ready() 应该被忽略,因为它会阻止所有内容,这可能是真的,因为当我删除这个 ready() 我的聊天不再有效,但是它启用了客户端断开检测 .

为了达到我的目标,我需要测试 BufferedReader 是否通过 readLine() 收到null但是这不应该正常工作 .

if (this.in.readLine()!=null){ //1. check if client disconnected
                if (this.in.ready())       //2/
                    this.dataIn=this.in.readLine(); //3.
            }                    
            else
                this.notice="Client disconnected!";

现在当我应用上面提到的代码时会发生什么 . 初始if if(1)阻塞内部 ready() (第2行),这是读取通过套接字(3)发送实际消息所必需的 .

另一个“订单”不起作用:

if (this.in.ready()){
                this.dataIn=this.in.readLine();
            }
            else if (this.in.readLine()!=null)
                this.notice="Client disconnected!";

这个也不允许通过套接字发送消息 .

*是的,发送/接收是在单独的线程中实现的

  • BufferedReader仅初始化一次

线程源代码(如果任何1需要它来看看):

@Override
public void run() {
    try {
        if (this.isServer){            
            this.initServer();
            this.initProcessData(sSocket);
        } 
        else if (!this.isServer){
            this.initClient();
            this.initProcessData(clientSocket);
        }            
        this.initDone=true;

    } catch (IOException ex) {
        Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
    }

    while(this.initDone){
        try {
            Thread.sleep(100);
            if ((!this.dataOut.isEmpty())&&(this.dataOut!="")){                
                this.out.println(this.dataOut);
                this.out.flush();
                this.dataOut = "";
            }
            if (this.in.ready())
                this.dataIn=this.in.readLine();                   
        }
        catch (IOException ex) {
            Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (InterruptedException ex) {  
            this.initDone=false;
                Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
        }

        //System.out.println(this.notice);
    }

}

最糟糕的是,我已正确检测到客户端断开连接或我正在聊天 .

谁能让我知道我该怎么办才能将这两者结合在一起呢?任何帮助非常感谢 .

1 回答

  • 0

    考虑使用 java.io.ObjectInputStreamjava.io.ObjectOutputStream . 在单独的工作线程中使用阻塞 read() 方法,并循环直到它返回-1或引发异常 . 来回发送String对象 . 这样,您还可以使用换行符发送邮件 .

相关问题