| 9 | |
| 10 | public class TestUdp { |
| 11 | public static void main(String[] args) throws IOException { |
| 12 | var udp = new DatagramSocket(0, InetAddress.getLoopbackAddress()); |
| 13 | var port = udp.getLocalPort(); |
| 14 | System.out.println(port); |
| 15 | |
| 16 | var udp2 = new DatagramSocket(0, InetAddress.getLoopbackAddress()); |
| 17 | var buf = "datagram".getBytes(StandardCharsets.UTF_8); |
| 18 | udp2.send(new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", port))); |
| 19 | |
| 20 | var recv = new byte[1024]; |
| 21 | var p = new DatagramPacket(recv, recv.length); |
| 22 | udp.receive(p); |
| 23 | |
| 24 | System.out.println(p.getLength()); |
| 25 | var message = new String(p.getData(), 0, p.getLength(), StandardCharsets.UTF_8); |
| 26 | System.out.println(message); |
| 27 | |
| 28 | udp.close(); |
| 29 | udp2.close(); |
| 30 | } |
| 31 | } |