用户在登录系统时,出现网络断开,从而系统自动检测到网络状态。
/**
* @author 麦克劳林
* @功能:持续检测网络是否连通
*/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NetState implements Runnable {
public static void main(String[] args) {
// TODO Auto-generated method stub
NetState ns = new NetState();
new Thread(ns).start();//启动线程
}
// 判断网络状态
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);
}
}
} 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() {
// TODO Auto-generated method stub
while (true) {
this.isConnect();
try {
// 每隔3秒钟测试一次网络是否连通
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}