<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
    實(shí)現(xiàn)方式 : 根據(jù)不同的情況可分為如下兩種

        直接調(diào)用監(jiān)控服務(wù)器的ping命令去測(cè)試需要監(jiān)控的設(shè)備
        通過指定服務(wù)器測(cè)試能否ping通 需要監(jiān)控的設(shè)備 (運(yùn)用Mina實(shí)現(xiàn) )

    下面將給出上述的兩種實(shí)現(xiàn)的詳細(xì)過程:

     

    一、直接調(diào)用服務(wù)器本身的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("請(qǐng)求超時(shí)") || 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;
        }

    }
    二、通過指定服務(wù)器去ping測(cè)試
           主要思路:利用Mina在指定的第三方服務(wù)器上運(yùn)行server端,然后實(shí)現(xiàn)客戶端和 第三方 服務(wù)器建立socket連接,發(fā)送ping任務(wù)的消息給第三方服務(wù)器,第三方服務(wù)器再把執(zhí)行結(jié)果實(shí)時(shí)反饋給客戶端。

           代碼包括四個(gè)類:

        服務(wù)端: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 + "發(fā)生異常:" + 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 + "發(fā)出消息:" + 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("服務(wù)端已啟動(dòng),監(jiān)聽端口:" + 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 + "發(fā)生異常:" + pCause.getLocalizedMessage());
        }

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

        @Override
        public void messageSent(IoSession pSession, Object pMessage)
                throws Exception {
            System.out.println(logId + "發(fā)出消息:" + 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停止系統(tǒng)運(yùn)行不關(guān)閉電源命令halt
            DefaultIoFilterChainBuilder chain = connector.getFilterChain();

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

            // 注冊(cè)消息處理器
            connector.setHandler(new PingClientIoHandler());
            connector.setConnectTimeoutMillis(30 * 1000L);
            // 連接服務(wù)器
            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("-------------------");
        }

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

            DefaultIoFilterChainBuilder chain = connector.getFilterChain();

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

            // 注冊(cè)消息處理器
            connector.setHandler(new PingClientIoHandler());
            connector.setConnectTimeoutMillis(30 * 1000L);
            // 連接服務(wù)器
            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) 評(píng)論(0)  編輯  收藏

    只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


    網(wǎng)站導(dǎo)航:
     
    人人游戲網(wǎng) 軟件開發(fā)網(wǎng) 貨運(yùn)專家
    主站蜘蛛池模板: 免费看黄的成人APP| 中文日韩亚洲欧美制服| 亚洲综合无码AV一区二区| 亚洲精品天堂成人片?V在线播放| 国产免费变态视频网址网站| 国产精品国产免费无码专区不卡| 日本免费人成视频播放 | 亚洲人成网网址在线看| 亚洲精品国产成人中文| 亚洲狠狠狠一区二区三区| 亚洲乱码卡三乱码新区| 2019亚洲午夜无码天堂| 亚洲欧洲无码AV不卡在线| 亚洲日韩精品无码AV海量| 国产精品亚洲专区无码WEB| 国产综合成人亚洲区| 国产精品99爱免费视频| 国产AV无码专区亚洲AWWW | 可以免费看黄视频的网站| 成年女人色毛片免费看| 成人午夜18免费看| 免费在线观看你懂的| 久久精品国产精品亚洲| 亚洲av无码一区二区三区网站| 久久久久亚洲AV无码网站| 亚洲AV无码一区二区三区人| 欧美日韩亚洲精品| 巨胸狂喷奶水视频www网站免费| 一个人免费视频观看在线www| 麻豆高清免费国产一区| 午夜一级免费视频| 亚洲综合久久夜AV | 亚洲精品在线观看视频| 一个人免费高清在线观看| 四虎影视永久免费视频观看| 亚洲色精品88色婷婷七月丁香| 亚洲无成人网77777| 国产亚洲视频在线观看网址| a毛片免费观看完整| 亚洲第一成年免费网站| 亚洲狠狠爱综合影院婷婷|