package com.njcn.utils.Kafka;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class ZookeeperServerStatus {

    /**********************************************
     * host  主机IP
     * port  端口
     **********************************************/
    public String serverStatus(String host, int port) throws IOException {
        String strModel = "";
        String cmd = "stat";

        Socket sock = new Socket(host, port);
        BufferedReader reader = null;
        try {
            OutputStream outstream = sock.getOutputStream();
            // 通过Zookeeper的四字命令获取服务器的状态
            outstream.write(cmd.getBytes());
            outstream.flush();
            sock.shutdownOutput();

            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.indexOf("Mode: ") != -1) {
                    strModel = line.replaceAll("Mode: ", "").trim();
                    break;
                }
            }
        } finally {
            sock.close();
            if (reader != null) {
                reader.close();
            }
        }
        return strModel;
    }
}
