软件工程师成长日记

判断监听系统网络状态

2018-02-10  本文已影响12人  麦克劳林
package com.asset.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date
import javax.servlet.http.HttpSession;
public class NetworkState implements Runnable {
private HttpSession session;
public void setSession (HttpSession session){
    this.session = session;
}
// 判断网络状态  
public void isConnect() {  
    Runtime runtime = Runtime.getRuntime();  
    try {  
        Process process = runtime.exec("ping " + "www.baidu.com");  
        InputStream is = process.getInputStream();  
        InputStreamReader isr = new InputStreamReader(is);  
        BufferedReader br = new BufferedReader(isr);  
        String line = null;  
        StringBuffer sb = new StringBuffer();  
        while ((line = br.readLine()) != null) {  
            sb.append(line);  
            // System.out.println("返回值为:"+line);  
        }  
        is.close();  
        isr.close();  
        br.close();  
  
        if (null != sb && !sb.toString().equals("")) {  
            String logString = "";  
            if (sb.toString().indexOf("TTL") > 0) {  
                // 网络畅通
                logString = "网络正常,时间: " + this.getCurrentTime();  
                System.out.println(logString);
            } else {  
                // 网络不畅通  
                logString = "网络断开,时间: " + this.getCurrentTime();  
                System.out.println(logString);
                session.invalidate();   
                return;
            }    
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  
  
// 获得当前时间  
public String getCurrentTime() {  
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    String time = sdf.format(new Date());  
    return time;  
}  

@Override
public void run() {  
    while (true) {  
        this.isConnect();
        try {  
            // 每隔3秒钟测试一次网络是否连通  
            Thread.sleep(3000);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
    }  
}
}
上一篇下一篇

猜你喜欢

热点阅读