1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| package com.sympa.lesson01;
import org.junit.jupiter.api.Test;
import java.io.IOException; import java.net.*; import java.nio.charset.StandardCharsets;
public class UDPTest {
@Test public void sender(){ try { DatagramSocket socket = new DatagramSocket(); String str = "UDP消息发送"; byte[] data = str.getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(data, 0, data.length, InetAddress.getLocalHost(), 8888);
socket.send(packet); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
@Test public void receiver(){ DatagramSocket socket = null; DatagramPacket packet = null; try { socket = new DatagramSocket(8888);
byte[] data = new byte[100]; packet = new DatagramPacket(data, 0, data.length); socket.receive(packet); System.out.println(new String(packet.getData(), 0, packet.getLength())); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
|