套接字读取()和就绪()互锁,客户端断开连接检测

问题描述:

好吧,我的问题很简单。我试图做简单的聊天,但我觉得从服务器断开客户端的检测是强制性的。聊天工作正常(没有这样的检测),当我使用简单:套接字读取()和就绪()互锁,客户端断开连接检测

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

我浏览过很多贴在这里的网站/问题,我读到ready()应该因为它阻止一切被中省略,这可能是真的,因为当我删除此ready()我的聊天不再有效,但它使客户端断开连接的检测。

为了达到我的目标,我需要测试BufferedReader是否通过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!"; 

现在当我应用上面提供的代码时会发生什么。如果(1)阻塞内部ready()(第2行)(如果需要读取通过套接字(3)发送的实际消息),则返回初始值。

其他“订单”不工作:

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

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

*是,发送/ recieving因而可实现单独的线程

* BufferedReader中被初始化一次

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

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

} 

最糟糕的是,我有适当的客户端断开检测或我有工作聊天。

任何人都可以让我知道我应该怎么做才能将这两者结合在一起?任何帮助不胜感激。

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