最近在開發中遇到一個問題,就是如何判斷遠端伺服器是否已經中斷連線,如果斷開那麼需要重新串連。
首先想到socket類的方法isClosed()、isConnected()、isInputStreamShutdown()、isOutputStreamShutdown()等,但經過實驗並查看相關文檔,這些方法都是本地端的狀態,無法判斷遠端是否已經中斷連線。
然後想到是否可以通過OutputStream發送一段測試資料,如果發送失敗就表示遠端已經中斷連線,類似ping,但是這樣會影響到正常的輸出資料,遠端無法把正常資料和測試資料分開。
最後又回到socket類,發現有一個方法sendUrgentData,查看文檔後得知它會往輸出資料流發送一個位元組的資料,只要對方Socket的SO_OOBINLINE屬性沒有開啟,就會自動捨棄這個位元組,而SO_OOBINLINE屬性預設情況下就是關閉的,太好了,正是我需要的。
於是,下面一段代碼就可以判斷遠端是否斷開了串連:
try{ socket.sendUrgentData(0xFF); }catch(Exception ex){ reconnect(); }
————————————————————————————————————————————————
呵呵。下面是本人寫的監聽串連程式:
/** * 監聽連接線程 * */ class MonitorConnect extends Thread{ private SocketStatus ss = null; private String address = null; private int Port = 0; public MonitorConnect(SocketStatus ss,String address,int Port){ this.ss = ss; this.address = address; this.Port = Port; } public void run(){ while(true){ if(ss.getSocket() == null){ SocketAddress socketaddress = new InetSocketAddress(address,Port); try{ Socket socket = new Socket(); socket.connect(socketaddress,5000); boolean status = true; while(status){ try{ socket.sendUrgentData(0xFF); ss.setSocket(socket); Thread.sleep(1000); }catch(Exception e1){ System.out.println("伺服器斷開。。"); ss.setSocket(null); status = false; } } }catch(Exception e){ System.out.println("串連失敗,3秒後重新串連"+e.getMessage()); } } try{ Thread.sleep(3000); }catch(Exception e){ System.out.println(e.getMessage()); } } } }