2012-01-31 2 views
0

내 문제는 간단합니다. 간단한 채팅을하려고하지만 서버에서 연결이 끊어진 클라이언트를 검색하는 것이 필수적이라고 생각합니다. 내가 간단한 사용하면 채팅 (예 : 감지없이) 잘 작동 : 언제부터 사실 일 수,소켓 읽기() 및 준비() 연동, 클라이언트 연결 감지

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

내가 여기에 게시 웹 사이트/많은 질문을 탐색하고 난 ready()이 블록의 모든 때문에 ommited해야한다고 읽기 전 이 ready() 채팅을 삭제하면 더 이상 작동하지 않지만 클라이언트 연결이 끊어지는 것을 감지 할 수 있습니다.

BufferedReaderreadLine()을 통해 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 (1)은 실제 메시지를 읽는 데 필요한 내부 ready() (줄 2)을 차단합니다. send over socket (3).

다른 "순서"작동하지 않습니다

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

이것은 또한 소켓을 통해 메시지를 보낼 수 없습니다.

은 예, 전송/잡은 별도의 스레드에서 실현 * (any1가 살펴하기 위해 그것을 필요로한다면)

*이 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); 
    } 

} 

최악의 경우 클라이언트 연결이 끊어 졌거나 채팅 중임을 감지하고 있습니다.

나는이 두 가지를 결합하기 위해 내가해야 할 일을 누군가가 할 수 있습니까? 어떤 도움이라도 대단히 감사합니다.

답변

0

java.io.ObjectInputStreamjava.io.ObjectOutputStream을 사용하는 것을 고려하십시오. 별도의 작업자 스레드에서 blocking read() 메서드를 사용하고 -1을 반환하거나 예외를 throw 할 때까지 반복합니다. String 객체를 앞뒤로 보냅니다. 그런 식으로 라인 피드로 메시지를 보낼 수도 있습니다.