socket查看zookeeper情况(4字命令)

本文介绍了一个用于发送四字命令的Java程序实现,该程序能够连接到指定主机和端口,发送四字命令并接收服务器响应。文章详细展示了如何设置Socket超时,连接到服务器,发送命令以及读取响应数据。
public class FourLetterWordMain {

    private static final int DEFAULT_SOCKET_TIMEOUT = 5000;
    protected static final Logger LOG = LoggerFactory.getLogger(FourLetterWordMain.class);

    /**
     * Send the 4letterword
     * @param host the destination host
     * @param port the destination port
     * @param cmd the 4letterword
     * @return server response
     * @throws java.io.IOException io exceptions
     */
    public static String send4LetterWord(String host, int port, String cmd)
            throws IOException {
        return send4LetterWord(host, port, cmd, DEFAULT_SOCKET_TIMEOUT);
    }
    /**
     * Send the 4letterword
     * @param host the destination host
     * @param port the destination port
     * @param cmd the 4letterword
     * @param timeout in milliseconds, maximum time to wait while connecting/reading data
     * @return server response
     * @throws java.io.IOException io exceptions
     */
    public static String send4LetterWord(String host, int port, String cmd, int timeout)
            throws IOException {
        LOG.info("connecting to " + host + " " + port);
        Socket sock = new Socket();
        InetSocketAddress hostaddress= host != null ? new InetSocketAddress(host, port) :
                new InetSocketAddress(InetAddress.getByName(null), port);
        BufferedReader reader = null;
        try {
            sock.setSoTimeout(timeout);
            sock.connect(hostaddress, timeout);
            OutputStream outstream = sock.getOutputStream();
            outstream.write(cmd.getBytes());
            outstream.flush();
            // this replicates NC - close the output stream before reading
            sock.shutdownOutput();

            reader =
                    new BufferedReader(
                            new InputStreamReader(sock.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } catch (SocketTimeoutException e) {
            throw new IOException("Exception while executing four letter word: " + cmd, e);
        } finally {
            sock.close();
            if (reader != null) {
                reader.close();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值