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 establish a connection, a connection port occupies 20 * of DatagramPacket 2. Create a data packet, the data packet sent to the specified port occupied ports behavior does not occur 21 * 3 send behavior 22 * 4. Close connector 23 * 24 * @param 25 * @return 26 is * @author 27 * @date 2019/7/23 10:51 28 * / 29 @Test 30 public void udpSend () throws IOException { 31 is DatagramSocket = DatagramSocket new new DatagramSocket (9999 ); 32 MSG = String "MSG msg66666666666666!" ; 33 is of DatagramPacket DatagramPacket = new new of DatagramPacket (Msg.getBytes (), Msg.getBytes () length,. New new the InetSocketAddress ( "localhost", 6666 )); 34 is DatagramSocket.send (DatagramPacket); 35 datagramSocket.close (); 36 } 37 [ 38 is / ** 39 * receiving UDP data: 40 * 1. establish a connection DatagramSocket, occupy the port connection is established. Note: This port is connected to monitor received transmission of one transport port DatagramPacket 41 * 2. Create a data packet DatagramPacket; storing the received data only, no longer listening port 42 * 3. Receiving acts 43 * 3.1 cycles into the receive process is carried out without receiving the transmission data congestion, received through the 44 actual length data and the reception data received by the acquired 3.2 * actual packet acquisition datagramPacket 45 * 4. Close connector 46 * 47 * @param 48 * @return 49 * @author 50 * @date 2019/7/23 10:51 51 is * / 52 is @Test 53 is public void udpRecive () throws IOException { 54 is DatagramSocket Client = new new DatagramSocket (6666); / / STEP. 1 55 byte [] bytes = new 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(); //3.2 STEP 64 65 System.out.println (COUNT + "Received Data Times:" + new new String (Data, 0 , length)); 66 COUNT ++ ; 67 } 68 System.out.println ( "reception times runs out, the program exits ! " ); 69 client.close (); 70 } 71 is 72 }
Process Summary: establishing a connection (corresponding to the connection release operation), the establishment of a data storage objects (for, buffers, etc.), the specific operation (associated objects connected to the data storage, then perform specific behavior)