Java监听指定端口通过udp协议接收与发送报文
创建服务端用于监听端口
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; /** * @author aaron * @since 2021-01-27 */ @Slf4j public class UdpServer { public static void main(String[] args) throws IOException { socketListener(); } public static void socketListener() throws IOException { log.info("端口监听进程开始启动"); //创建socket 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 socket.close(); } } }
创建客户端用于发送报文
import com.lanlinker.netty.paycard.util.HexConvert; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.net.*; /** * @author aaron * @since 2021-01-27 */ @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); //参数1.数据 2.数据长度 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进制字符串的方法
//将字节数组转换为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; /** * @author aaron * @since 2021-01-27 */ public class Test { public static void main(String[] args){ //16进制的 报文 数组 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); } }
上一篇:
Java架构师技术进阶路线图