android ip冲突检测工具,android ping ip 来检测连接是否正常

起因

设备的运行环境原因,网络时不时的断开,tcp的连接使用别人的服务,没有心跳包来监听是否断开。

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 断开连接");

} catch (Exception e) {

e.printStackTrace();

judgment("Exception Process 断开连接");

}

}

}

in.read(byte[] bytes):方式是阻塞的,有数据触发往下走。物理连接断开的时候,能收到 IO异常。但是数据链路层断开了(ping ip 返回 1 ),这里是不汇报异常的(具体原因也不知道,可能是底层)。

通过ping ip 来监听网络是否断开

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的次数 3是指ping 3次 ,-w 100 以秒为单位指定超时间隔,是指超时时间为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, "运行了");

}

}

}

最好是有心跳包来检测是否断开。(我这里暂时不支持)

通过间隔的ping tcp连接的ip ,来判断连接是否终端。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值