package com.mmh.xxx;
import lombok.extern.slf4j.Slf4j;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/**
* @Description: 描述:发送UPD报文并接收数据响应
* @Author mmh
* @Date 2022/10/18 17:26
*/
@Slf4j
public class UDPUtils {
/** 定义每个数据报的最大大小为4KB */
public static final int DATA_LEN = 4096;
/** 定义接收网络数据的字节数组 */
public static byte[] inBuff = new byte[DATA_LEN];
/** 地址 */
public static String BROADCAST_URL = "127.0.0.1";
/** 端口 */
public static Integer BROADCAST_PORT = 8080;
public static String USER_PASS = "xxxx";
/**
* 发送UDP请求
* @param message 组装好的UDP请求报文 (包括操作指令,用户密码之类的)
* @return
*/
public static String sendMessage(String message) throws Exception {
log.info("发送UDP: {},{},{}", BROADCAST_URL, BROADCAST_PORT, message);
try (DatagramSocket socket = new DatagramSocket()) {
InetSocketAddress inetSocketAddress = new InetSocketAddress(BROADCAST_URL, BROADCAST_PORT);
// 防止出现乱码
byte[] udpMessage = message.getBytes("gbk");
DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
DatagramPacket outPacket = new DatagramPacket(udpMessage, udpMessage.length, inetSocketAddress);
socket.setSoTimeout(50000);
socket.send(outPacket);
socket.receive(inPacket);
// 编码格式与上面对应
String result = new String(inPacket.getData(), 0, inPacket.getLength(), "gbk");
log.info("数据响应:" + result);
if (!socket.isClosed()) {
socket.close();
}
return result;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new Exception("请求失败!!!");
}
}
public static void main(String[] args) throws Exception {
sendMessage("CALL_STOP;" + USER_PASS +";"+ "xxx编号" +";");
System.out.println();
}
}
01-30
3739
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-26
6902
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-10
849
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)