可以使用socket類中的sendUrgentData方法,該方法會往輸出流發(fā)送一個字節(jié)的數(shù)據(jù),只要對方Socket的SO_OOBINLINE屬性沒有打開,就會自動舍棄這個字節(jié),而SO_OOBINLINE屬性默認情況下就是關(guān)閉的。
于是,下面一段代碼就可以判斷遠端是否斷開了連接:
try{ socket.sendUrgentData(0xFF); }catch(Exception ex){ reconnect(); }
(免費學習視頻教程分享:java視頻教程)
用ping實現(xiàn):
package com.csdn.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class test { static BufferedReader bufferedReader; public static void main(String[] args) throws IOException { try { Process process = Runtime.getRuntime().exec("ping 192.168.1.104");//判斷是否連接的IP; bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String connectionStr = ""; while ((connectionStr = bufferedReader.readLine()) != null) { System.out.println(connectionStr); } } catch (IOException e) { e.printStackTrace(); } finally { bufferedReader.close(); } } }
注意:此方法有一個嚴重的不足之處,就是你只能判斷對方是否連接網(wǎng)絡,而不能判斷客戶端是否開啟。
其實在通過socket.getoutstream和socket.getinputstream流對客戶端發(fā)送、接受信息時如果socket沒連接上是會拋出異常的,這也就是為什么Java會要求網(wǎng)絡編程都要寫在try里面,所以只要在catch里面寫入客戶端退出的處理就行了。
相關(guān)文章教程推薦:java入門教程