udp进行数据发送与接收

1:udp发送(这是广播局域网的形式,可以修改为指定IP地址)

 @SneakyThrows
 public static void main(String[] args) {
     String message="中文";
     DatagramSocket dgSocket = new DatagramSocket();
     byte[] bytes = message.getBytes();
     DatagramPacket dgPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("255.255.255.255"), 9000);
     dgSocket.send(dgPacket);
     dgSocket.close();
 }

2:udp接收

@SneakyThrows
public static void main(String[] args) {
    DatagramSocket dgSocket = new DatagramSocket(9000); // 监听端口号为9000
    byte[] buffer = new byte[1024];
    DatagramPacket dgPacket = new DatagramPacket(buffer, buffer.length);
    while (true) {
        dgSocket.receive(dgPacket); // 接收数据包
        String message = new String(dgPacket.getData(), 0, dgPacket.getLength());
        System.out.println("接收到广播消息: " + message);
        // 在这里对接收到的消息进行处理
        // 清空数据包,以便下次接收
        dgPacket.setLength(buffer.length);
    }   
}

注意:在Java中,我们可以使用DatagramSocket和DatagramPacket这两个类来进行UDP数据包的接收和发送操作。其中,DatagramSocket用于创建一个UDP套接字,并侦听指定的端口号;而DatagramPacket则表示一个UDP数据包,可以在网络上进行发送和接收。所以,如果你想要接收UDP数据包,可以使用DatagramSocket来创建一个UDP套接字,并在循环中调用receive()方法来接收数据包。如果你想要发送UDP数据包,则可以使用DatagramPacket类来构建数据包,并调用send()方法将其发送到目标地址

2:udp接收到数据即给发送者返回消息(注意:发送着的监听端口需要开通才能接收到消息)

 public static void main(String args[]) throws Exception {
     DatagramSocket serverSocket = new DatagramSocket(9000);
     byte[] receiveData = new byte[1024];
     byte[] sendData;
     while (true) {
         DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
         serverSocket.receive(receivePacket);
         String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
         InetAddress IPAddress = receivePacket.getAddress();
         int port = receivePacket.getPort();
         System.out.println("Heartbeat received from: " + IPAddress.getHostAddress() + ":" + port);
         // 发送数据
         String responseMessage = "Hello, device!";
         sendData = responseMessage.getBytes();
         DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
         serverSocket.send(sendPacket);
     }

你可能感兴趣的:(udp,网络协议,网络)