在 Android socket 編程中我們需要時刻對其網絡狀態進行判斷,android對網絡狀態判斷的方法(isClosed(),isConnected(),isInputShutdown(),sOutputShutdown())中都是判斷本地socket端的狀態的,無法判斷遠端的socket狀態,則可通過隔段時間向對方發送數據,如果發送過程出現異常,則證明網絡出現問題。
1.使用 sendUrgentData方法,需要設置遠端socket屬性setOOBInline(true)
public boolean sendHeartBeat() {
try {
mSocket.sendUrgentData(0xFF);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
2.通過發送TCP消息
public synchronized boolean sendHttpMsg(HttpMsg msg){
try {
msg.writeTo(mOutputStream);
mOutputStream.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
3.以上兩種方法貌似還可以使用,但是有種情況也是無效的,例如:對方單方向斷網(拔掉網線)。這種情況下就需要其他方法判斷了,可以使用Linux下的ping命令,這是目前最有效的網絡狀態判定,也是比較準確的方法。public boolean startPing(){
boolean success=false;
Process p =null;
try {
p = Runtime.getRuntime().exec("ping -c 3 -i 1 -W 5 " +BOX_IP_ADDRESS); //-c次數 -i間隔 -W超時
int status = p.waitFor();
if (status == 0) {
success=true;
} else {
success=false;
}
} catch (IOException e) {
success=false;
} catch (InterruptedException e) {
success=false;
}finally{
p.destroy();
}
return success;
}
這種方法會造成程序卡頓
4.採用服務器定時發送心跳包,客戶端檢測超時
mSocket.setSoTimeout(20000);
弊端是會增加通信消耗。