网络状态监控_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 网络状态监控

网络状态监控

 2014/6/27 21:32:42  larryscale  程序员俱乐部  我要评论(0)
  • 摘要:importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.text.SimpleDateFormat;importjava.util.Date;/***@功能
  • 标签:网络

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
?
/**
?* @功能:持续检测网络是否连通
?*/

public class NetworkState implements Runnable {
?public static void main(String[] args) {
??NetworkState ns = new NetworkState();
??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);
????}
????this.writeIntoLog(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;
?}

?// 将信息写入日志文件
?public void writeIntoLog(String logString) {
??File file = null;
??FileWriter fw = null;
??BufferedWriter bw = null;
??try {
???file = new File("D:\\netWorkState.log");
???if (!file.exists()) {
????file.createNewFile();// 如果不存在该文件,则创建
????String sets = "attrib +H \"" + file.getAbsolutePath() + "\"";
????//Runtime.getRuntime().exec(sets);// 将日志文件隐藏
???}
???fw = new FileWriter(file, true);
???bw = new BufferedWriter(fw);
???fw.append(logString + "\r\n");// 换行
??} catch (Exception e) {
???e.printStackTrace();
??} finally {
???try {
????bw.close();
????fw.close();
???} catch (IOException e) {
????e.printStackTrace();
???}
??}

?}

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

}

  • NetworkState.7z (1.2 KB)
  • 下载次数: 0
上一篇: 冒泡、选择、插入排序 下一篇: 没有下一篇了!
发表评论
用户名: 匿名