Networking
networking3UdpDatagram
- Path
- pkg10networking/networking3UdpDatagram.java
- Package
- pkg10networking
- Study order
- 3
- Run
- Single-file source launch
- Command
- java pkg10networking/networking3UdpDatagram.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg10networking;2 3import java.net.DatagramPacket;4import java.net.DatagramSocket;5import java.net.InetAddress;6 7/*8 * networking3UdpDatagram.java9 * ---------------------------10 * UDP datagrams: connectionless, unordered, best-effort messages.11 *12 * DEFINITION:13 * UDP sends independent packets (datagrams) with no connection, no ordering,14 * and no delivery guarantee — but with very low overhead. Good for DNS, video,15 * games, metrics. This demo sends a packet to itself over loopback.16 *17 * KEY POINTS:18 * - DatagramSocket sends/receives; DatagramPacket holds bytes + address + port.19 * - receive() blocks until a packet arrives (or timeout via setSoTimeout).20 * - No accept()/connect() handshake — just fire packets.21 * - Packets can be lost, duplicated, or reordered: the app must cope.22 */23public class networking3UdpDatagram {24 25 public static void main(String[] args) throws Exception {26 InetAddress loop = InetAddress.getLoopbackAddress();27 28 // Receiver socket on an OS-chosen port29 DatagramSocket receiver = new DatagramSocket(0);30 int port = receiver.getLocalPort();31 32 Thread receiverThread = new Thread(() -> {33 try {34 byte[] buf = new byte[1024];35 DatagramPacket packet = new DatagramPacket(buf, buf.length);36 receiver.receive(packet); // blocks until a datagram arrives37 String msg = new String(packet.getData(), 0, packet.getLength());38 System.out.println("[receiver] got: \"" + msg + "\" from port " + packet.getPort());39 } catch (Exception e) {40 System.out.println("[receiver] error: " + e.getMessage());41 }42 });43 receiverThread.start();44 45 // Sender fires one datagram at the receiver46 try (DatagramSocket sender = new DatagramSocket()) {47 byte[] data = "hello over UDP".getBytes();48 DatagramPacket packet = new DatagramPacket(data, data.length, loop, port);49 sender.send(packet);50 System.out.println("[sender] sent " + data.length + " bytes to port " + port);51 }52 53 receiverThread.join();54 receiver.close();55 System.out.println("Done.");56 }57}