0

好的,我的问题很简单。我正在尝试进行简单的聊天,但我觉得检测与服务器断开连接的客户端是强制性的。当我使用简单时,聊天工作正常(没有这种检测):

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

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

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

            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 (1) 阻塞内部ready()(第 2 行),这是读取通过套接字 (3) 发送的实际消息所需的。

另一个“命令”不起作用:

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

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

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

*BufferedReader 只初始化一次

线程源代码(如果需要它以查看):

    @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);
    }

}

最糟糕的是,我要么正确检测到客户端断开连接,要么正在聊天。

谁能启发我我应该怎么做才能将这两者结合在一起?非常感谢任何帮助。

4

1 回答 1

0

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

于 2012-01-31T21:34:38.520 回答