创建服务端用于监听端口
import com.lanlinker.netty.paycard.entity.DoorSendMessage;
import com.lanlinker.netty.paycard.util.HexConvert;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
@Slf4j
public class UdpServer {
public static void main(String[] args) throws IOException {
socketListener();
}
public static void socketListener() throws IOException {
log.info("端口监听进程开始启动");
DatagramSocket socket = new DatagramSocket(8800);
byte[] buf = new byte[64];
try {
DatagramPacket recPacket = new DatagramPacket(buf, buf.length);
socket.receive(recPacket);
InetAddress address = recPacket.getAddress();
String targetIp = address.getHostAddress();
int targetPort = recPacket.getPort();
log.info("=========接收到来自" + targetIp + ":" + targetPort + "的消息:" + HexConvert.BinaryToHexString(buf));
System.out.println(HexConvert.BinaryToHexString(buf));
int port = recPacket.getPort();
UdpClient.send(targetIp, port, new DoorSendMessage().getMessage());
socket.close();
} catch (Exception e) {
} finally {
socket.close();
}
}
}
创建客户端用于发送报文
import com.lanlinker.netty.paycard.util.HexConvert;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.*;
@Slf4j
public class UdpClient {
public static void send(String ip, int port, byte[] content) {
try {
DatagramSocket socket = new DatagramSocket();
SocketAddress socketAddress = new InetSocketAddress(ip, port);
DatagramPacket packet = new DatagramPacket(content, content.length, socketAddress);
String str = HexConvert.BinaryToHexString(content);
log.info("目标IP:" + ip + ",目标端口:" + port + ",发送的报文:" + str);
socket.send(packet);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
将字节数组转换为16进制字符串的方法
public static String BinaryToHexString(byte[] bytes) {
String hexStr = "0123456789ABCDEF";
String result = "";
String hex = "";
for (byte b : bytes) {
hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
hex += String.valueOf(hexStr.charAt(b & 0x0F));
result += hex + " ";
}
return result;
}
创建测试类
import com.lanlinker.netty.paycard.server.UdpClient;
public class Test {
public static void main(String[] args){
byte[] message = new byte[1024];
message[0] = (byte) 0x01;
message[1] = (byte) 0x02;
message[2] = (byte) 0x03;
message[3] = (byte) 0x04;
message[4] = (byte) 0x05;
message[8] = (byte) 0x0E;
UdpClient.send("127.0.0.1", 8800, message);
}
}
Springboot持续监听端口 并通过udp协议收发报文