posts - 241,  comments - 116,  trackbacks - 0
          實現方式 : 根據不同的情況可分為如下兩種

              直接調用監控服務器的ping命令去測試需要監控的設備
              通過指定服務器測試能否ping通 需要監控的設備 (運用Mina實現 )

          下面將給出上述的兩種實現的詳細過程:

           

          一、直接調用服務器本身的ping命令

          TestPingCmd.java
          package michael.net;

          import java.io.BufferedReader;
          import java.io.File;
          import java.io.FileReader;
          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.LineNumberReader;
          import java.text.MessageFormat;
          import java.util.ArrayList;
          import java.util.List;
          import java.util.concurrent.ArrayBlockingQueue;
          import java.util.concurrent.ThreadPoolExecutor;
          import java.util.concurrent.TimeUnit;

          /**
           * @blog http://sjsky.iteye.com
           * @author Michael
           */
          public class TestPingCmd {

              /**
               * @param args
               * @throws Exception
               */
              public static void main(String[] args) throws Exception {

                  // 讀取txt文件中的IP列表
                   TestPingCmd pinger = new TestPingCmd();
                  List<String> iplist = pinger
                          .getIpListFromTxt("d:/test/idc_ping_ip.txt");

                  // List<String> iplist = new ArrayList<String>();
                  // iplist.add("222.*.*.*");
                  // iplist.add("222.*.*.*");
                  // iplist.add("222.*.*.*");
                  // iplist.add("222.*.*.*");
                  // iplist.add("222.*.*.*");
                  ThreadPoolExecutor executorPool = new ThreadPoolExecutor(50, 60, 60,
                          TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50),
                          new ThreadPoolExecutor.CallerRunsPolicy());
                  long startTime = System.currentTimeMillis();
                  final int maxCount = 4;
                  for (final String ip : iplist) {
                      executorPool.execute(new Runnable() {
                          public void run() {
                              TestPingCmd pinger = new TestPingCmd();
                              Integer countSucce = pinger.doPingCmd(ip, maxCount);
                              if (null != countSucce) {
                                  System.out.println("host:[ " + ip + " ] ping cout: "
                                          + maxCount + " success: " + countSucce);

                              } else {
                                  System.out
                                          .println("host:[ " + ip + " ] ping cout null");
                              }
                          }

                      });
                  }
                  while (executorPool.getActiveCount() > 0) {
                      Thread.sleep(100);
                  }
                  System.out.println("complete ping jobs count = " + iplist.size()
                          + " , total used time(ms) = "
                          + (System.currentTimeMillis() - startTime));
                  executorPool.shutdown();
              }

              /**
               * @param destIp
               * @param maxCount
               * @return
               */
              public Integer doPingCmd(String destIp, int maxCount) {
                  LineNumberReader input = null;
                  try {
                      String osName = System.getProperties().getProperty("os.name");
                      String pingCmd = null;
                      if (osName.startsWith("Windows")) {
                          pingCmd = "cmd /c ping -n {0} {1}";
                          pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
                      } else if (osName.startsWith("Linux")) {
                          pingCmd = "ping -c {0} {1}";
                          pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
                      } else {
                          System.out.println("not support OS");
                          return null;
                      }
                      Process process = Runtime.getRuntime().exec(pingCmd);
                      InputStreamReader ir = new InputStreamReader(process
                              .getInputStream());
                      input = new LineNumberReader(ir);
                      String line;
                      List<String> reponse = new ArrayList<String>();

                      while ((line = input.readLine()) != null) {
                          if (!"".equals(line)) {
                              reponse.add(line);
                              // System.out.println("====:" + line);
                          }
                      }
                      if (osName.startsWith("Windows")) {
                          return parseWindowsMsg(reponse, maxCount);
                      } else if (osName.startsWith("Linux")) {
                          return parseLinuxMsg(reponse, maxCount);
                      }

                  } catch (IOException e) {
                      System.out.println("IOException   " + e.getMessage());

                  } finally {
                      if (null != input) {
                          try {
                              input.close();
                          } catch (IOException ex) {
                              System.out.println("close error:" + ex.getMessage());

                          }
                      }
                  }
                  return null;
              }

              private int parseWindowsMsg(List<String> reponse, int total) {
                  int countTrue = 0;
                  int countFalse = 0;
                  for (String str : reponse) {
                      if (str.startsWith("來自") || str.startsWith("Reply from")) {
                          countTrue++;
                      }
                      if (str.startsWith("請求超時") || str.startsWith("Request timed out")) {
                          countFalse++;
                      }
                  }
                  return countTrue;
              }

              private int parseLinuxMsg(List<String> reponse, int total) {
                  int countTrue = 0;
                  for (String str : reponse) {
                      if (str.contains("bytes from") && str.contains("icmp_seq=")) {
                          countTrue++;
                      }
                  }
                  return countTrue;
              }

              /**
               * @param filepath
               * @return list
               */
              public List<String> getIpListFromTxt(String filepath) {
                  BufferedReader br = null;
                  List<String> iplist = new ArrayList<String>();
                  try {
                      File file = new File(filepath);
                      br = new BufferedReader(new FileReader(file));
                      while (br.ready()) {
                          String line = br.readLine();
                          if (null != line && !"".equals(line)) {
                              iplist.add(line);
                          }
                      }
                  } catch (Exception e) {
                      e.printStackTrace(System.out);

                  } finally {
                      if (null != br) {
                          try {
                              br.close();
                          } catch (Exception ex) {
                              ex.printStackTrace(System.out);
                          }
                      }
                  }
                  return iplist;
              }

          }
          二、通過指定服務器去ping測試
                 主要思路:利用Mina在指定的第三方服務器上運行server端,然后實現客戶端和 第三方 服務器建立socket連接,發送ping任務的消息給第三方服務器,第三方服務器再把執行結果實時反饋給客戶端。

                 代碼包括四個類:

              服務端:PingServerIoHandler.java PingServer.java
              客戶端:PingClientIoHandler.java PingClient.java
          package michael.mina.ping;

          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.LineNumberReader;
          import java.text.MessageFormat;

          import org.apache.mina.core.service.IoHandlerAdapter;
          import org.apache.mina.core.session.IdleStatus;
          import org.apache.mina.core.session.IoSession;

          /**
           * @blog http://sjsky.iteye.com
           * @author Michael
           */
          public class PingServerIoHandler extends IoHandlerAdapter {
              private String logId = "SERVER:: ";
              private int msgCount = 0;

              @Override
              public void exceptionCaught(IoSession pSession, Throwable pCause)
                      throws Exception {
                  System.out.println(logId + "發生異常:" + pCause.getLocalizedMessage());
              }

              @Override
              public void messageReceived(IoSession pSession, Object pMessage)
                      throws Exception {
                  String msg = String.valueOf(pMessage);
                  msgCount++;
                  System.out.println(logId + "收到客戶端第 " + msgCount + " 條消息:" + msg);
                  pSession.write(msgCount);

                  if (msg.startsWith("ping")) {
                      String destIp = msg.split(" ")[1];
                      doPingCmd(pSession, destIp);
                  }

              }

              @Override
              public void messageSent(IoSession pSession, Object pMessage)
                      throws Exception {
                  System.out.println(logId + "發出消息:" + pMessage);
              }

              @Override
              public void sessionClosed(IoSession pSession) throws Exception {
                  System.out.println(logId + "one client closed ");
              }

              @Override
              public void sessionCreated(IoSession pSession) throws Exception {
                  System.out.println(logId + "sessionCreated ");
              }

              @Override
              public void sessionIdle(IoSession pSession, IdleStatus pStatus)
                      throws Exception {
                  super.sessionIdle(pSession, pStatus);
              }

              @Override
              public void sessionOpened(IoSession pSession) throws Exception {
                  System.out.println(logId + "sessionOpened ");
              }

              private Integer doPingCmd(IoSession pSession, String destIp) {
                  LineNumberReader input = null;
                  int maxCount = 4;
                  try {
                      String osName = System.getProperties().getProperty("os.name");
                      String pingCmd = null;
                      if (osName.startsWith("Windows")) {
                          pingCmd = "cmd /c ping -n {0} {1}";
                          pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
                      } else if (osName.startsWith("Linux")) {
                          pingCmd = "ping -c {0} {1}";
                          pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
                      } else {
                          System.out.println("not support OS");
                          return null;
                      }
                      Process process = Runtime.getRuntime().exec(pingCmd);
                      InputStreamReader ir = new InputStreamReader(process
                              .getInputStream());
                      input = new LineNumberReader(ir);
                      String line;

                      while ((line = input.readLine()) != null) {
                          if (!"".equals(line)) {
                              pSession.write(line);
                          }
                      }
                  } catch (IOException e) {
                      System.out.println("IOException   " + e.getMessage());

                  } finally {
                      if (null != input) {
                          try {
                              input.close();
                          } catch (IOException ex) {
                              System.out.println("close error:" + ex.getMessage());

                          }
                      }
                  }
                  return null;
              }
          }
          package michael.mina.ping;

          import java.net.InetSocketAddress;
          import java.nio.charset.Charset;

          import org.apache.mina.core.service.IoAcceptor;
          import org.apache.mina.filter.codec.ProtocolCodecFilter;
          import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
          import org.apache.mina.filter.logging.LoggingFilter;
          import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

          /**
           * @blog http://sjsky.iteye.com
           * @author Michael
           */
          public class PingServer {

              private static final int PORT = 54321;

              /**
               * @param args
               * @throws Exception
               */
              public static void main(String[] args) throws Exception {
                  IoAcceptor acceptor = new NioSocketAcceptor();

                  acceptor.getFilterChain().addLast("logger", new LoggingFilter());
                  acceptor.getFilterChain().addLast(
                          "codec",
                          new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                                  .forName("UTF-8"))));
                  acceptor.setHandler(new PingServerIoHandler());
                  acceptor.bind(new InetSocketAddress(PORT));

                  System.out.println("服務端已啟動,監聽端口:" + PORT);

              }

          }
          package michael.mina.ping;

          import org.apache.mina.core.service.IoHandlerAdapter;
          import org.apache.mina.core.session.IdleStatus;
          import org.apache.mina.core.session.IoSession;

          /**
           * @blog http://sjsky.iteye.com
           * @author Michael
           */
          public class PingClientIoHandler extends IoHandlerAdapter {

              private String logId = "CLIENT:: ";

              @Override
              public void exceptionCaught(IoSession pSession, Throwable pCause)
                      throws Exception {
                  System.out.println(logId + "發生異常:" + pCause.getLocalizedMessage());
              }

              @Override
              public void messageReceived(IoSession pSession, Object pMessage)
                      throws Exception {
                  String count = String.valueOf(pMessage);
                  System.out.println(logId + "服務端收到的消息數 = " + count);
              }

              @Override
              public void messageSent(IoSession pSession, Object pMessage)
                      throws Exception {
                  System.out.println(logId + "發出消息:" + pMessage);
              }

              @Override
              public void sessionClosed(IoSession pSession) throws Exception {
                  System.out.println(logId + "one client closed ");
              }

              @Override
              public void sessionCreated(IoSession pSession) throws Exception {
                  System.out.println(logId + "sessionCreated ");
              }

              @Override
              public void sessionIdle(IoSession pSession, IdleStatus pStatus)
                      throws Exception {
                  super.sessionIdle(pSession, pStatus);
              }

              @Override
              public void sessionOpened(IoSession pSession) throws Exception {
                  System.out.println(logId + "sessionOpened ");
              }
          }
          package michael.mina.ping;

          import java.net.InetSocketAddress;
          import java.nio.charset.Charset;
          import java.util.ArrayList;
          import java.util.List;
          import java.util.Scanner;

          import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
          import org.apache.mina.core.future.ConnectFuture;
          import org.apache.mina.core.session.IoSession;
          import org.apache.mina.filter.codec.ProtocolCodecFilter;
          import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
          import org.apache.mina.transport.socket.SocketConnector;
          import org.apache.mina.transport.socket.nio.NioSocketConnector;

          /**
           * @blog http://sjsky.iteye.com
           * @author Michael
           */
          public class PingClient {

              private static final int PORT = 54321;

              /**
               * IP列表
               * @param ipList
               */
              public void createPingClient(List<String> ipList) {
                  SocketConnector connector = new NioSocketConnector();Linux停止系統運行不關閉電源命令halt
                  DefaultIoFilterChainBuilder chain = connector.getFilterChain();

                  // 設定過濾器一行一行讀取數據
                  chain.addLast("codec", new ProtocolCodecFilter(
                          new TextLineCodecFactory(Charset.forName("UTF-8"))));

                  // 注冊消息處理器
                  connector.setHandler(new PingClientIoHandler());
                  connector.setConnectTimeoutMillis(30 * 1000L);
                  // 連接服務器
                  ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
                          54321));
                  cf.awaitUninterruptibly();
                  IoSession session = cf.getSession();
                  for (String ip : ipList) {
                      session.write("ping " + ip);
                  }
                  session.getCloseFuture().awaitUninterruptibly();
                  connector.dispose();
                  System.out.println("-------------------");
              }

              /**
               * 控制臺輸入
               * @param ipList
               */
              public void createPingClient() {
                  SocketConnector connector = new NioSocketConnector();

                  DefaultIoFilterChainBuilder chain = connector.getFilterChain();

                  // 設定過濾器一行一行讀取數據
                  chain.addLast("codec", new ProtocolCodecFilter(
                          new TextLineCodecFactory(Charset.forName("UTF-8"))));

                  // 注冊消息處理器
                  connector.setHandler(new PingClientIoHandler());
                  connector.setConnectTimeoutMillis(30 * 1000L);
                  // 連接服務器
                  ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
                          54321));
                  cf.awaitUninterruptibly();
                  IoSession session = cf.getSession();
                  Scanner input = new Scanner(System.in).useDelimiter("\\r\\n");
                  while (input.hasNext()) {
                      String s = input.next();
                      if (s.equals("quit")) {
                          break;
                      }
                      session.write(s);
                  }
                  // cf.getSession().getCloseFuture().awaitUninterruptibly();
                  connector.dispose();
              }

              /**
               * @param args
               * @throws Exception
               */
              public static void main(String[] args) throws Exception {
                  PingClient tester = new PingClient();
                  List<String> iplist = new ArrayList<String>();
                  iplist.add("192.168.8.89");
                  iplist.add("192.168.8.93");
                  iplist.add("192.168.8.109");
                  iplist.add("192.168.8.117");
                  iplist.add("192.168.8.118");
                  tester.createPingClient(iplist);
              }

          }

          posted on 2011-07-22 09:19 墻頭草 閱讀(8020) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          人人游戲網 軟件開發網 貨運專家
          主站蜘蛛池模板: 大洼县| 维西| 都兰县| 清丰县| 阿克苏市| 灌云县| 修武县| 邵东县| 仲巴县| 麻栗坡县| 福贡县| 新宁县| 磐石市| 新竹市| 荔波县| 鹿邑县| 嘉兴市| 香港| 德令哈市| 英吉沙县| 大埔县| 枣强县| 古蔺县| 台州市| 嘉峪关市| 杨浦区| 旺苍县| 太保市| 盘山县| 太和县| 邓州市| 彭山县| 黔江区| 横山县| 平泉县| 托克托县| 长兴县| 抚顺县| 外汇| 聂拉木县| 小金县|