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 ,来判断连接是否终端。

你可能感兴趣的:(android ping ip 来检测连接是否正常)