2013-03-14 22 views
0

誰能告訴我爲什麼我在得到此異常sc.connectClosedChannelException

(SC =的SocketChannel)

/** 
* Verify socket is connected. If not currently connected will attempt to connect 
* @return true if already connected or connection successfully established 
*/ 
private synchronized boolean verifyConnection() { 
    if (sc.isConnected()) { 
     return true; 
    } 
    try { 
     if (!sc.isOpen()) { 
      logger.info("Channel WebBroker->CC is CLOSED unexpectedly. Opening new channel " + getIpAddress() + ":" + getIpPort() + ""); 
      openChannel(); 
     } 
     sc.socket().close(); 
     sc.connect(new InetSocketAddress(getIpAddress(), getIpPort())); 
     while(!sc.finishConnect()){ 
      Thread.sleep(1);  
     } 
     logger.info("Connection established " + getIpAddress() + ":" + getIpPort()); 
     sc.socket().setKeepAlive(true); 
     return sc.isConnected(); 
    } catch (Exception e) { 
     logger.info("failed to connect to " + getIpAddress() + ":" + getIpPort(), e); 
     return false; 
    } 
} 


private void openChannel() throws Exception { 
    sc = SocketChannel.open(); 
    sc.socket().setKeepAlive(true); 
    sc.socket().setSoTimeout(30000); 
} 

[錯誤]無法連接到10.201.1.53:8084

java.nio.channels.ClosedChannelException: null 
    at sun.nio.ch.SocketChannelImpl.ensureOpenAndUnconnected(SocketChannelImpl.java:472) ~[na:1.6.0_07] 
    at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:486) ~[na:1.6.0_07] 

編輯:最後我發現這是因爲下面的線。

sc.socket().close(); 

回答

0

您無法重新連接套接字。你必須創建一個新的。

您還應該注意isConnected()只會告訴您是否曾連接過套接字。它不會告訴你整個連接的當前狀態。同樣的,isOpen()只會告訴你你是否還沒有關閉它:不是對方是否這樣做。一般情況下,你不能寫出你正在編寫的方法。判斷TCP連接是否仍然存在的唯一可靠方法是寫入它。一般來說,檢測是否有任何資源可用的唯一可靠方法是嘗試使用它。不要試圖預測未來。無論如何,你仍然必須處理寫入失敗:爲什麼要寫所有的代碼兩次?

+0

嗨,我正在重新連接?請告訴我如何創建一個新的套接字而不是重新連接? – 2013-03-14 21:57:51

相關問題