Socket 监控服务器运行状态

想使用socket写一个跨服务器通信的监控小软件,用于收集服务器信息,雏形如下

服务端类

package test.serv;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

public class Server {

    public static void main(String[] args) {
        
        // 启动3000端口
        int argnum = args.length;
        if (argnum < 2) {
            System.out.println("请输入IP地址、端口,比如:172.17.201.127 3000");
            return;
        }
        String ipaddr = getIP(args[0]);
        int port = Integer.valueOf(args[1]);
        startService(ipaddr,port);
        /*
        startService("10.168.150.107",3000);
        */
    }    
        
    /**     * 开启3000端口
     */
    public static void startService(String ipaddr,int port){
        ServerSocket server;
        BufferedReader br = null;
        try{
            server = new ServerSocket();
            server.setReuseAddress(true);
            server.bind(new InetSocketAddress(ipaddr,port));
            Socket sk = null;
            String context = "---服务器端开始接收消息-----";
            String filePath = "./log/"+getlognamebyweek();
            boolean isAppend = true;
            String encoding = "UTF-8";
            while(true){
                sk = server.accept();
                context="<-------服务器端开始接收消息----------->\n\r";
                writeStringToFile(context, filePath, isAppend, encoding);
                br = new BufferedReader(
                        new InputStreamReader(sk.getInputStream()));
                context=br.readLine();
                writeStringToFile(context, filePath, isAppend, encoding);
                br.close();
                context="\n\r<-------服务器端结束接收消息----------->\n\r";
                writeStringToFile(context, filePath, isAppend, encoding);
            }
            
            
        }catch(IOException e){
            System.out.println(e);
        }finally{
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void writeStringToFile(String context, String filePath, boolean isAppend, String encoding)
      {
        BufferedWriter bfw = null;
        try {
          bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, isAppend), encoding));
          bfw.write(context);
          bfw.flush();
          bfw.close();
        }
        catch (IOException localIOException1)
        {
          try
          {
            if (bfw != null)
              bfw.close();
          }
          catch (IOException e)
          {
            e.printStackTrace();
          }
        }
        finally
        {
          try
          {
            if (bfw != null)
              bfw.close();
          }
          catch (IOException e)
          {
            e.printStackTrace();
          }
        }
      }
    
    /**
     * 将主机名解析为IP
     * @param name
     * @return
     */
    public static String getIP(String name) {
        String pattern = "^[0-9]+.[0-9]+.[0-9]+.[0-9]+$";
        boolean isIP = Pattern.matches(pattern, name);
        if (isIP) {
            return name;
        }
        InetAddress address = null;
        try {
            address = InetAddress.getByName(name);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            System.out.println("获取失败");
        }
        return address.getHostAddress().toString();
    }
    
    /**
     * 周一至周日每天一个日志
     * @return
     */
    public static String getlognamebyweek(){
          
          Date date=new Date();
          Calendar c=Calendar.getInstance();
          c.setTime(date);
          //今天是这个星期的第几天
          int week=c.get(Calendar.DAY_OF_WEEK)-1;
          return week+".log";
      }
}

 

客户端类

package test.serv;

import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

public class Client {
    public static void main(String args[]){
        // 启动3000端口
        int argnum = args.length;
        if (argnum != 3) {
            System.out.println("请输入IP地址、端口,比如:172.17.201.127 3000 msg");
            return;
        }
        
        String ipaddr = getIP(args[0]);
        int port = Integer.valueOf(args[1]);
        String msg = args[2];
        
        Socket client;
        PrintStream ps;
        try{
            client = new Socket(ipaddr,port);
            System.out.println("客户端连接成功");
            ps = new PrintStream(client.getOutputStream());
            ps.println(msg);
            ps.close();
            client.close();
        }catch(IOException e){
            System.out.println();
        }
    }
    
    /**
     * 将主机名解析为IP
     * @param name
     * @return
     */
    public static String getIP(String name) {
        String pattern = "^[0-9]+.[0-9]+.[0-9]+.[0-9]+$";
        boolean isIP = Pattern.matches(pattern, name);
        if (isIP) {
            return name;
        }
        InetAddress address = null;
        try {
            address = InetAddress.getByName(name);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            System.out.println("获取失败");
        }
        return address.getHostAddress().toString();
    }
}

测试

将编程后的.class类上传到服务器上

在被监控机上执行

[root@a12cdg1 scripts]# java test/serv/Server a12cdg1 3000

在监控机上执行

[root@a12csh4 scripts]# java test/serv/Client a12cdg1 3000 "磁盘使用率50%"
客户端连接成功

查看日志输出

[root@a12cdg1 log]# tailf 1.log

<-------服务器端开始接收消息----------->
磁盘使用率50%
<-------服务器端结束接收消息----------->

用于内部监控,网络不出内网,且限定了IP,安全上也没问题,这样两个服务器上就建立了基于TCP/IP的通信渠道,具体的监控内容计划使用python书写,然后以json方式返回给Java Socket。

 

posted @ 2017-12-18 18:56  我是DBA  阅读(2924)  评论(0编辑  收藏  举报