1 package com.temp; 2 3 4 import org.junit.Test; 5 6 import java.io.*; 7 import java.net.DatagramPacket; 8 import java.net.DatagramSocket; 9 import java.net.InetSocketAddress; 10 11 /** 12 * @author 13 * @date 2019/7/23 14 */ 15 public class TestUdp { 16 17 /** 18 * udp 发送数据: 19 * 1.建立通信DatagramSocket,占用端口建立通信 20 * 2.创建数据包DatagramPacket,指定数据包发向的端口,不会发生端口占用行为 21 * 3.发送行为 22 * 4.关闭通信 23 * 24 * @param 25 * @return 26 * @author 27 * @date 2019/7/23 10:51 28 */ 29 @Test 30 public void udpSend() throws IOException { 31 DatagramSocket datagramSocket = new DatagramSocket(9999); 32 String msg = "msg msg66666666666666!"; 33 DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, new InetSocketAddress("localhost", 6666)); 34 datagramSocket.send(datagramPacket); 35 datagramSocket.close(); 36 } 37 38 /** 39 * udp 接收数据: 40 * 1.建立通信DatagramSocket,占用端口建立通信。注意:该连接监听接收端口为发送一方的DatagramPacket的传输端口 41 * 2.创建数据包DatagramPacket;仅作为接收数据的存储,无需再监听端口 42 * 3.接收行为 43 * 3.1 进入循环后receive方法在没有收到发送数据时进行堵塞,收到则通过 44 * 3.2 接收的数据及接收数据的实际长度由获取到的实际数据包datagramPacket获取 45 * 4.关闭通信 46 * 47 * @param 48 * @return 49 * @author 50 * @date 2019/7/23 10:51 51 */ 52 @Test 53 public void udpRecive() throws IOException { 54 DatagramSocket client = new DatagramSocket(6666); //step 1 55 byte[] bytes = new byte[1024]; 56 DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); 57 int count = 0; 58 while (count < 3) { 59 System.out.println("into circle!"); 60 client.receive(datagramPacket); //step 3.1 61 System.out.println("passed receive!"); 62 byte[] data = datagramPacket.getData(); //step 3.2 63 int length = datagramPacket.getLength(); //step 3.2 64 65 System.out.println(count + "times received data:" + new String(data, 0, length)); 66 count++; 67 } 68 System.out.println("接收次数用完,退出程序!"); 69 client.close(); 70 } 71 72 }
流程总结:建立通信对象(对应释放通信对象动作),建立数据存储对象(包,缓冲区等),具体操作(关联连接与数据存储对象,再执行具体行为)
来源:https://www.cnblogs.com/swz1104919/p/11230784.html