<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    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 墻頭草 閱讀(8019) 評論(0)  編輯  收藏

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


    網站導航:
     
    人人游戲網 軟件開發網 貨運專家
    主站蜘蛛池模板: 亚洲精品无码不卡在线播HE| 国产V亚洲V天堂无码| 精品亚洲成A人无码成A在线观看| 日韩精品无码专区免费播放| 亚洲精品国产美女久久久| 中文字幕免费在线视频| 国产亚洲日韩一区二区三区| 中文字幕不卡高清免费| 国产亚洲美女精品久久久久狼 | 18禁成年无码免费网站无遮挡| 亚洲AV中文无码乱人伦下载 | 亚洲欧美日本韩国| 色窝窝免费一区二区三区| 国产91在线|亚洲| 成年午夜视频免费观看视频 | 亚洲国产老鸭窝一区二区三区 | 中文字幕无码精品亚洲资源网久久| 16女性下面扒开无遮挡免费| 亚洲一卡二卡三卡| 国产精品另类激情久久久免费| 青娱乐在线免费观看视频| 亚洲中文字幕无码一久久区| 免费视频一区二区| 99热亚洲色精品国产88| 亚洲国产成人精品91久久久| a毛片免费全部播放完整成| 亚洲视频手机在线| 国产在线19禁免费观看| 中文字幕免费视频精品一| 亚洲精品在线免费观看| 免费被黄网站在观看| 久久免费99精品国产自在现线| 亚洲色偷偷偷网站色偷一区| 国产精品久久香蕉免费播放| 中国精品一级毛片免费播放| 亚洲午夜一区二区电影院| 国产亚洲精品免费| 日韩内射激情视频在线播放免费| 亚洲中文字幕久久久一区| 亚洲香蕉成人AV网站在线观看| 国产乱子精品免费视观看片|