package net.test.com.common.util;
import lombok.extern.slf4j.Slf4j;
import net.test.com.common.exception.domain.baseException;
import java.io.*;
import java.net.Socket;
@Slf4j
public class SocketClient {
public static Socket getConnection(String ip, int port) {
Socket socket = null;
try {
socket = new Socket(ip, port);
socket.setSoTimeout(30000);
} catch (IOException e) {
log.error("获取socket连接失败", e);
throw new baseException("获取socket连接失败");
}
return socket;
}
private static String send(Socket socket, String cmd) {
InputStream in = null;
OutputStream out = null;
BufferedReader br = null;
try {
// in代表服务器到客户端的流
in = socket.getInputStream();
// 代表客户端到服务器的流
out = socket.getOutputStream();
// 输入执行命令
PrintWriter printWriter = new PrintWriter(out, true);
printWriter.println(cmd);
printWriter.flush();
// 接收执行命令结果
br = new BufferedReader(new InputStreamReader(in));
return br.readLine();
} catch (Exception e) {
log.error("调用socket失败", e);
throw new baseException("调用socket失败");
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void close(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
log.error("socket关闭失败", e);
throw new baseException("socket关闭失败");
}
}
}
public static String sendSocketMessage(String host, int port, String msg) {
Socket socket = null;
String response = null;
try {
socket = getConnection(host, port);
response = send(socket, msg);
} finally {
close(socket);
}
return response;
}
public static void main(String args[]) {
String resp = sendSocketMessage("122.15.1.138", 5015, "reload vcc 782rnrn");
log.info("socket返回:{}", resp);
}
}