TCP协议工具类
@Log4j
public class TcpUtils {
public static void sendHexStrToByteArrayMessage(String host, int port, String message) throws Exception {
if (StringUtils.isEmpty(host)) {
host = "127.0.0.1";
}
Thread.sleep(120);
Socket socket = new Socket(host, port);
boolean connected = socket.isConnected();
if (connected) {
log.info("连接成功 发送消息: " + message);
OutputStream out = socket.getOutputStream();
byte[] bytes = hexStrToByteArray(message);
if (!StringUtils.isEmpty(bytes)) {
out.write(bytes);
socket.shutdownOutput();
log.info("发送指令成功!");
}
out.close();
socket.close();
}
}
public static byte[] hexStrToByteArray(String hexString) {
byte[] bytes = null;
if (!StringUtils.isEmpty(hexString)) {
hexString = hexString.replaceAll(" ", "");
int len = hexString.length();
int index = 0;
bytes = new byte[len / 2];
while (index < len) {
String sub = hexString.substring(index, index + 2);
bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
index += 2;
}
}
return bytes;
}
public static void sendDecimalMessage(String host, Integer port, String message) throws IOException {
log.info("发送消息:" + message);
Socket socket = new Socket(host, port);
boolean connected = socket.isConnected();
if (connected) {
log.info("连接服务成功");
OutputStream out = socket.getOutputStream();
out.write(message.getBytes(StandardCharsets.UTF_8));
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = reader.readLine();
log.info("返回消息:" + readLine);
socket.close();
}
}
public static void decimalMessage(String host, Integer port, String message) throws Exception {
if (StringUtils.isEmpty(host)) {
host = "127.0.0.1";
}
Thread.sleep(120);
Socket socket = new Socket(host, port);
boolean connected = socket.isConnected();
if (connected) {
log.info("连接成功 发送消息: " + message);
OutputStream out = socket.getOutputStream();
out.write(message.getBytes("GBK"));
socket.shutdownOutput();
socket.close();
}
}
}
UDP协议工具类
**
* UDP协议
*
* @ClassName: UdpUtils
* @Version: 1.0
*/
public class UdpUtils {
public static String sendUdpMessage(String host, Integer port, String message) throws Exception {
String replyMessage = "";
if (StringUtils.isEmpty(host)) {
host = "127.0.0.1";
}
DatagramSocket socket = new DatagramSocket();
byte[] buf = message.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(host), port);
socket.send(packet);
try {
socket.setSoTimeout(2000);
byte[] data =new byte[1024];
DatagramPacket packet1 = new DatagramPacket(data,data.length);
socket.receive(packet1);
replyMessage = new String(data,0,packet1.getLength());
} catch (IOException e) {
replyMessage = "";
} finally {
socket.close();
}
return replyMessage;
}
}
|