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 {
/**
* 获取socket连接
*
* @param ip
* @param port
* @return
*/
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;
}
/**
* 发送报文
*
* @param socket
* @param cmd
* @return
*/
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();
}
}
}
}
/**
* 关闭socket连接
*
* @param socket
*/
private static void close(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
log.error("socket关闭失败", e);
throw new BaseException("socket关闭失败");
}
}
}
/**
* 发送消息
*
* @param host
* @param port
* @param msg
*/
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 782\r\n\r\n");
log.info("socket返回:{}", resp);
}
}
Java的socket实例
于 2022-03-15 10:15:41 首次发布