起因
設(shè)備的運(yùn)行環(huán)境原因,網(wǎng)絡(luò)時(shí)不時(shí)的斷開(kāi),tcp的連接使用別人的服務(wù),沒(méi)有心跳包來(lái)監(jiān)聽(tīng)是否斷開(kāi)。
public void run() {
while (isRunning) {
byte[] btAryBuffer = new byte[1024];
try {
int nLenRead = DealWidth.this.in.read(btAryBuffer);
if (nLenRead > 0) {
byte[] btAryReceiveData = new byte[nLenRead];
System.arraycopy(btAryBuffer, 0, btAryReceiveData, 0, nLenRead);
for (ConnectState item : mState) {
item.message(btAryReceiveData);
}
DealWidth.this.mPackageParser.runReceiveDataCallback(btAryReceiveData,
DealWidth.this.mPackageProcess);
}
} catch (IOException e) {
judgment("IOException Process 斷開(kāi)連接");
} catch (Exception e) {
e.printStackTrace();
judgment("Exception Process 斷開(kāi)連接");
}
}
}
in.read(byte[] bytes):方式是阻塞的,有數(shù)據(jù)觸發(fā)往下走。物理連接斷開(kāi)的時(shí)候,能收到 IO異常。但是數(shù)據(jù)鏈路層斷開(kāi)了(ping ip 返回 1 ),這里是不匯報(bào)異常的(具體原因也不知道,可能是底層)。
通過(guò)ping ip 來(lái)監(jiān)聽(tīng)網(wǎng)絡(luò)是否斷開(kāi)
public class PingIpThread implements Runnable {
private static final String TAG = PingIpThread.class.getSimpleName();
private boolean isRunning = true;
private String pingIp = "www.baidu.com";
private int timeOut = 3;
public void setRunning(boolean running) {
isRunning = running;
}
public void setPingIp(String pingIp) {
this.pingIp = pingIp;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
@Override
public void run() {
Runtime runtime = Runtime.getRuntime();
while (isRunning) {
try {
//ping -c 3 -w 100 中,-c 是指ping的次數(shù) 3是指ping 3次 ,-w 100 以秒為單位指定超時(shí)間隔,是指超時(shí)時(shí)間為100秒
Process p = runtime.exec("ping -c 3 -w " + timeOut + " " + pingIp);
int ret = p.waitFor();
Log.d(TAG, "" + ret);
if (ret == 0) {
//成功
} else {
//ping ip 失敗,可能為 1 或者 2
}
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Exception:" + e.getMessage());
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "運(yùn)行了");
}
}
}
最好是有心跳包來(lái)檢測(cè)是否斷開(kāi)。(我這里暫時(shí)不支持)
通過(guò)間隔的ping tcp連接的ip ,來(lái)判斷連接是否終端。