Socket通信 多线程Windows/Linux系统检查 (CPU、内存、PING、线程)

主要通过Socket访问部署在Windows或Linux系统上的JAVA服务,获取系统的信息(包括CPU、内存、PING、线程)

 

import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import java.util.concurrent.*;

import sun.management.ManagementFactory;

import com.sun.management.OperatingSystemMXBean;

public class MultiThreadServer {

      private int port = 8821;

      private ServerSocket serverSocket;

      private ExecutorService executorService;

      private final int POOL_SIZE = 10;

      public static void main(String[] args) throws IOException {
            new MultiThreadServer().service();
      }

      /**
       * start server
       */
      public MultiThreadServer() throws IOException {
            serverSocket = new ServerSocket(port);
            executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
                        .availableProcessors()
                        * POOL_SIZE);
            System.out.println("start server");
      }

      /**
       * greate connect server listen
       */
      public void service() {
            while (true) {
                  Socket socket = null;
                  try {
                        socket = serverSocket.accept();
                        executorService.execute(new Handler(socket));
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }

      class Handler implements Runnable {
            private Socket socket;

            private String pingdb = "";

            private String pingetl = "";

            private String pingzk = "";

            /** cpu Sleep Time * */
            private static final int CPUTIME = 30;

            private static final int PERCENT = 100;

            private static final int FAULTLENGTH = 10;

            private static final int outTime = 3000;

            public Handler(Socket socket) {
                  this.socket = socket;
            }

            private PrintWriter getWriter(Socket socket) throws IOException {
                  OutputStream socketOut = socket.getOutputStream();
                  return new PrintWriter(socketOut, true);
            }

            private BufferedReader getReader(Socket socket) throws IOException {
                  InputStream socketIn = socket.getInputStream();
                  return new BufferedReader(new InputStreamReader(socketIn));
            }

            public void run() {
                  try {
                        BufferedReader br = getReader(socket);
                        String msg = br.readLine();
                        String strPW = "";
                        String[] str = msg.split("//|");
                        if (msg.toUpperCase().startsWith("PING")) {
                              if (str.length > 1) {
                                    System.out.println("PING:" + str[1]);
                                    if (!str[1].equals("PING"))
                                          pingdb = str[1];
                                    if (!str[2].equals("PING"))
                                          pingzk = str[2];
                                    if (!str[3].equals("PING"))
                                          pingetl = str[3];
                              }
                              strPW = getSystemInfo();
                              System.out.println(strPW);
                        }
                        PrintWriter pw = getWriter(socket);
                        pw.println(strPW);
                  } catch (IOException e) {
                        e.printStackTrace();
                  } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  } finally {
                        try {
                              if (socket != null)
                                    socket.close();
                        } catch (IOException e) {
                              e.printStackTrace();
                        }
                  }
            }

            /**
             * PING Test
             *
             * @param ip
             *            PING IP Address
             * @param outtime
             * @return true ;false
             */
            public boolean ping(String ip, int outtime) {
                  boolean bool = false;
                  try {
                        if (ip.length() > 0) {
                              InetAddress address = InetAddress.getByName(ip);
                              if (address.isReachable(outtime)) {
                                    bool = true;
                              }
                        }
                  } catch (UnknownHostException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
                  return bool;
            }

            /**
             * get listen bo
             *
             * @return result
             * @throws Exception
             */
            public String getSystemInfo() throws Exception {
                  int kb = 1024;

                  OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
                              .getOperatingSystemMXBean();

                  // System name
                  String osName = System.getProperty("os.name");
                  // total physical memory
                  long totalPhysicalMemory = osmxb.getTotalPhysicalMemorySize() / kb;
                  // user physical memory
                  long usedPhysicalMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
                              .getFreePhysicalMemorySize())
                              / kb;

                  // get total Thread
                  ThreadGroup parentThread;
                  for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
                              .getParent() != null; parentThread = parentThread
                              .getParent())
                        ;
                  int totalThread = parentThread.activeCount();

                  double cpuRatio = 0;
                  if (osName.toLowerCase().startsWith("windows")) {
                        System.out.println("get Windows System CPU info!");
                        cpuRatio = this.getCpuRatioForWindows();
                  } else {
                        System.out.println("get Linux System CPU info!");
                        cpuRatio = getCpuInfo();
                  }

                  InetAddress addr = InetAddress.getLocalHost();
                  String ip = addr.getHostAddress().toString();// get IP

                  StringBuffer sb = new StringBuffer();
                  sb.append("<?xml version=/"1.0/" encoding=/"GBK/" ?>");
                  sb.append("<tables tableCount=/"1/">");
                  sb
                              .append("<table name=/"SYSINFO/"  rowCount=/"1/" fieldCount=/"6/">");
                  sb.append("<row rowId=/"0/">");
                  sb.append("<field name=/"TYPE/">").append("DB").append("</field>");
                  sb.append("<field name=/"IP/">").append(ip).append("</field>");
                  sb.append("<field name=/"OS/">").append(osName).append("</field>");
                  String strboolping = "false";
                  if (pingdb != null && !pingdb.equals("")) {
                        if (ping(pingdb, outTime)) {
                              strboolping = "true";
                        } else {
                              strboolping = "false";
                        }
                        sb.append("<field name=/"PINGDB/">").append(strboolping)
                                    .append("</field>");
                  }
                  if (pingzk != null && !pingzk.equals("")) {
                        if (ping(pingzk, outTime)) {
                              strboolping = "true";
                        } else {
                              strboolping = "false";
                        }
                        sb.append("<field name=/"PINGZK/">").append(strboolping)
                                    .append("</field>");
                  }
                  if (pingetl != null && !pingetl.equals("")) {
                        if (ping(pingetl, outTime)) {
                              strboolping = "true";
                        } else {
                              strboolping = "false";
                        }
                        sb.append("<field name=/"PINGETL/">").append(strboolping)
                                    .append("</field>");
                  }
                  sb.append("<field name=/"MEMORY/">").append(
                              totalPhysicalMemory + "|" + usedPhysicalMemory).append(
                              "</field>");
                  sb.append("<field name=/"THREAD/">").append(totalThread).append(
                              "</field>");
                  sb.append("<field name=/"CPU/">").append(cpuRatio).append(
                              "</field>");
                  sb.append("</row>");
                  sb.append("</table>");
                  sb.append("</tables>");

                  return sb.toString();
            }

 

       private double getCpuInfo() throws IOException, InterruptedException {
                  File file = new File("/proc/stat");
                  BufferedReader br = new BufferedReader(new InputStreamReader(
                              new FileInputStream(file)));
                  StringTokenizer token = new StringTokenizer(br.readLine());
                  token.nextToken();
                  int user1 = Integer.parseInt(token.nextToken());
                  int nice1 = Integer.parseInt(token.nextToken());
                  int sys1 = Integer.parseInt(token.nextToken());
                  int idle1 = Integer.parseInt(token.nextToken());

                  Thread.sleep(1000);

                  br = new BufferedReader(new InputStreamReader(new FileInputStream(
                              file)));
                  token = new StringTokenizer(br.readLine());
                  token.nextToken();
                  int user2 = Integer.parseInt(token.nextToken());
                  int nice2 = Integer.parseInt(token.nextToken());
                  int sys2 = Integer.parseInt(token.nextToken());
                  int idle2 = Integer.parseInt(token.nextToken());
                  double doub = (double)((user2 + sys2 + nice2) - (user1 + sys1 + nice1))
                  / (double) ((user2 + nice2 + sys2 + idle2) - (user1 + nice1
                              + sys1 + idle1));
                 
                  java.text.DecimalFormat myformat=new java.text.DecimalFormat("#0.00");  
                  myformat.format(doub);  

                  return doub;
            }

            // private static void freeResource(InputStream is, InputStreamReader
            // isr,
            // BufferedReader br) {
            // try {
            // if (is != null)
            // is.close();
            // if (isr != null)
            // isr.close();
            // if (br != null)
            // br.close();
            // } catch (IOException ioe) {
            // System.out.println(ioe.getMessage());
            // }
            // }

            /**
             * get CPU user.
             *
             * @return cpu user
             */
            private double getCpuRatioForWindows() {
                  try {
                        String procCmd = System.getenv("windir")
                                    + "//system32//wbem//wmic.exe process get Caption,CommandLine,"
                                    + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";

                        long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
                        Thread.sleep(CPUTIME);
                        long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
                        if (c0 != null && c1 != null) {
                              long idletime = c1[0] - c0[0];
                              long busytime = c1[1] - c0[1];
                              return Double.valueOf(
                                          PERCENT * (busytime) / (busytime + idletime))
                                          .doubleValue();
                        } else {
                              return 0.0;
                        }
                  } catch (Exception ex) {
                        ex.printStackTrace();
                        return 0.0;
                  }
            }

            /**
             * read CPU info.
             *
             * @param proc
             * @return long[]
             */
            private long[] readCpu(final Process proc) {
                  long[] retn = new long[2];
                  try {
                        proc.getOutputStream().close();
                        InputStreamReader ir = new InputStreamReader(proc
                                    .getInputStream());
                        LineNumberReader input = new LineNumberReader(ir);
                        String line = input.readLine();
                        if (line == null || line.length() < FAULTLENGTH) {
                              return null;
                        }
                        int capidx = line.indexOf("Caption");
                        int cmdidx = line.indexOf("CommandLine");
                        int rocidx = line.indexOf("ReadOperationCount");
                        int umtidx = line.indexOf("UserModeTime");
                        int kmtidx = line.indexOf("KernelModeTime");
                        int wocidx = line.indexOf("WriteOperationCount");
                        long idletime = 0;
                        long kneltime = 0;
                        long usertime = 0;
                        while ((line = input.readLine()) != null) {
                              if (line.length() < wocidx) {
                                    continue;
                              }
                              // Caption,CommandLine,KernelModeTime,ReadOperationCount,
                              // ThreadCount,UserModeTime,WriteOperation
                              String caption = Bytesubstring(line, capidx, cmdidx - 1)
                                          .trim();
                              String cmd = Bytesubstring(line, cmdidx, kmtidx - 1).trim();
                              if (cmd.indexOf("wmic.exe") >= 0) {
                                    continue;
                              }
                              // log.info("line="+line);
                              if (caption.equals("System Idle Process")
                                          || caption.equals("System")) {
                                    idletime += Long.valueOf(
                                                Bytesubstring(line, kmtidx, rocidx - 1).trim())
                                                .longValue();
                                    idletime += Long.valueOf(
                                                Bytesubstring(line, umtidx, wocidx - 1).trim())
                                                .longValue();
                                    continue;
                              }

                              kneltime += Long.valueOf(
                                          Bytesubstring(line, kmtidx, rocidx - 1).trim())
                                          .longValue();
                              usertime += Long.valueOf(
                                          Bytesubstring(line, umtidx, wocidx - 1).trim())
                                          .longValue();
                        }
                        retn[0] = idletime;
                        retn[1] = kneltime + usertime;
                        return retn;
                  } catch (Exception ex) {
                        ex.printStackTrace();
                  } finally {
                        try {
                              proc.getInputStream().close();
                        } catch (Exception e) {
                              e.printStackTrace();
                        }
                  }
                  return null;
            }

            private String Bytesubstring(String src, int start_idx,
                        int end_idx) {
                  byte[] b = src.getBytes();
                  String tgt = "";
                  for (int i = start_idx; i <= end_idx; i++) {
                        tgt += (char) b[i];
                  }
                  return tgt;
            }
      }
}

 

调用格式为“PING|IP|IP|IP” IP为PING的目标

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值