~/ learn/ comp-348/ cards/ DatagramPacket and DatagramSocket
1 of 7

A UDP client: one request out, one response back

A UDP client: one request out, one response back

Answer

try (DatagramSocket socket = new DatagramSocket(0)) { socket.setSoTimeout(5000); InetAddress host = InetAddress.getByName("time.example.net"); socket.send(new DatagramPacket(new byte[1], 1, host, 13)); DatagramPacket response = new DatagramPacket(new byte[512], 512); socket.receive(response); String reply = new String(response.getData(), 0, response.getLength(), StandardCharsets.US_ASCII); }

Port 0 asks for an anonymous local port. The send packet carries the destination because the socket does not hold one. The three-argument String constructor is the only correct decode — getData() alone would append the unused 500-odd bytes of the buffer.

Harold 4e ch12 §UDP Clients; §UDP Servers; §The DatagramPacket Class

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/2d336e2b-f207-45d8-b1b5-00f8662b168d/flashcard utf-8 LF