image.png

    1. package com.atguigu.java2;
    2. import org.junit.Test;
    3. import java.io.IOException;
    4. import java.net.DatagramPacket;
    5. import java.net.DatagramSocket;
    6. import java.net.InetAddress;
    7. /**
    8. * @author Dxkstart
    9. * @create 2021-06-05 18:04
    10. */
    11. public class UDPTest {
    12. @Test
    13. public void send(){//发送端
    14. DatagramSocket socket = null;
    15. try {
    16. socket = new DatagramSocket();
    17. String str = "我是UDP发送的导弹";
    18. byte[] data = str.getBytes();
    19. InetAddress inet = InetAddress.getLocalHost();//本地地址
    20. DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
    21. //发送
    22. socket.send(packet);
    23. } catch (IOException e) {
    24. e.printStackTrace();
    25. } finally {
    26. try {
    27. if(socket != null) {
    28. socket.close();
    29. }
    30. } catch (Exception e) {
    31. e.printStackTrace();
    32. }
    33. }
    34. }
    35. @Test
    36. public void receiver() throws IOException {//接收端
    37. DatagramSocket socket = new DatagramSocket(9090);
    38. byte[] buffer = new byte[100];
    39. DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
    40. //接收数据
    41. socket.receive(packet);
    42. System.out.println(new String(packet.getData(),0,packet.getLength()));
    43. socket.close();
    44. }
    45. }