~/ learn/ comp-348/ cards/ IP, TCP, and UDP
1 of 5

Send the same bytes twice: once as a TCP stream, once as one UDP datagram

Send the same bytes twice: once as a TCP stream, once as one UDP datagram

Answer

byte[] page = body.getBytes(StandardCharsets.UTF_8); // the 3,150-byte page try (Socket tcp = new Socket(host, 80)) { // TCP cuts it up for you tcp.getOutputStream().write(page); } int max = 1500 - 20 - 8; // one datagram per MTU: 1472 try (DatagramSocket udp = new DatagramSocket()) { for (int off = 0; off < page.length; off += max) { // three datagrams, cut by you udp.send(new DatagramPacket(page, off, Math.min(max, page.length - off), host, 9)); } }

One payload, two transports, and every difference is in who does the work. The single TCP `write` becomes three segments that the far end reassembles in order without being asked. The UDP loop is you doing that cutting by hand, and nothing on the other side puts it back: lose the middle datagram and the receiver gets 1 and 3 with no idea 2 existed. Note also where the destination lives — in the `Socket` for TCP, in each `DatagramPacket` for UDP.

Harold 4e ch1 §IP, TCP, and UDP

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/78eaa69b-a0ad-446e-a9f2-f89ad93d7456/flashcard utf-8 LF