2011-01-10 59 views
0

我已經使用Apache Mina創建了一個TCP客戶端。我添加了一個while循環來不斷檢查端口的活性。一旦連接在服務器端,連接就會斷開並建立連接。我從未來開始討論並使用它進行交流。 有沒有更好的方法來做到這一點。而不是循環,我可以要求連接等到它結束。來自客戶端的Apache Mina TCP會話跟蹤

while(true){ 
    try { 
ConnectFuture future = ioConnector.connect(new InetSocketAddress(Port), 
      new TriggerReceiverHandler(), SOCKET_CONFIG); 
    System.out.println("Message Receiver started and listening on port "+ Port); 
Thread.sleep(1000); 
       session = future.getSession(); 
       if(session != null) 
        break; 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      }catch(Exception ce){ 
       if(ce.getCause() instanceof ConnectException) 
       System.out.println("Retrying connection"); 
      } 
     } 

另一個問題是,如果服務器宕機,我希望服務器保持等待,直到它建立連接,我應該怎麼辦?

回答

0

答案是,截至目前它不可能,因爲只有當我們嘗試連接時才知道連接狀態。一個修改是代替Thread.sleep(1000);,我們可以在版本1.0+中添加future.join(),或者在2.0+的情況下添加未來的收聽者。