socket串連,判斷串連中斷,如果中斷,並自動重連。

來源:互聯網
上載者:User

    最近在開發中遇到一個問題,就是如何判斷遠端伺服器是否已經中斷連線,如果斷開那麼需要重新串連。

      首先想到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());             }         }     } }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.