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();
}
}
}
}
socket查看zookeeper情况(4字命令)
最新推荐文章于 2024-09-30 21:44:26 发布
本文介绍了一个用于发送四字命令的Java程序实现,该程序能够连接到指定主机和端口,发送四字命令并接收服务器响应。文章详细展示了如何设置Socket超时,连接到服务器,发送命令以及读取响应数据。
378

被折叠的 条评论
为什么被折叠?



