1,UDP通信的程序组成:Socket

  1. 发送端:DatagramSocket();

image.png

  1. 1. 创建发送端;**DatagramSocket**
  1. DatagramSocket ds = new DatagramSocket();
  1. 2. 创建一个数据包;**DatagramPacket**![image.png](https://cdn.nlark.com/yuque/0/2022/png/25975946/1645492317122-942d06aa-7b8c-4119-b65a-d641cd52d496.png#clientId=u04b78c47-6df4-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=100&id=ud883e91f&margin=%5Bobject%20Object%5D&name=image.png&originHeight=100&originWidth=1083&originalType=binary&ratio=1&rotation=0&showTitle=false&size=29118&status=done&style=none&taskId=uff3ddab7-6057-4c06-98d2-f4856f4016b&title=&width=1083)
  1. byte[] bytes = "nh".getBytes();
  2. DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getLocalHost(), 8083);
  1. 3. 发送数据包;
  1. ds.send(dp);
  2. //
  3. ds.close();
  1. 接受端:DatagramSocket(int port);

    1. 创建接受端;

      1. //端口号和发送端一致;
      2. DatagramSocket ds = new DatagramSocket(8083);
    2. 创建一个空的数据包;

      1. byte[] bytes = new byte[1024];
      2. DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
    3. 接受数据包;

      1. ds.receive(dp);
      2. //获取数据包长度
      3. int length = dp.getLength();
      4. //将字节转字符输出:
      5. System.out.println(new String(bytes,0,length));