Belajar
← All lessons

How UDP works

Ask without a handshake

Laptop
Network
DNS server

resolver.js

const sock = dgram.createSocket("udp4"); function ask(query, tries = 3) {  sock.send(query, 53, "1.1.1.1");  const timer = setTimeout(() => {    // no answer? ask again    if (tries > 1) ask(query, tries - 1);  }, 2000);  sock.once("message", (answer) => {    clearTimeout(timer);    use(answer);  });}

dns-server.js

const sock = dgram.createSocket("udp4");sock.bind(53);// no accept() and nothing stored per clientsock.on("message", (query, from) => {  const answer = lookup(query);  sock.send(answer, from.port, from.address);});

An 8-byte header type a message and see the datagram

Message
Header fields
On the wire

That's the whole header. TCP's is at least 20 bytes, plus the connection behind it

udp.js

// nothing to open first, the header goes straight in front of the dataconst header = Buffer.alloc(8);header.writeUInt16BE(srcPort, 0);header.writeUInt16BE(dstPort, 2);header.writeUInt16BE(8 + data.length, 4);header.writeUInt16BE(checksum(ips, header, data), 6);send(Buffer.concat([header, data]));

Lose some on the way then compare what the app gets

ProtocolUDPTCP
Packets the network loses20%
What the app gets, in the order it gets it
delivered
out of order
last read

Games and video calls would rather skip a late frame than wait for it, so they pick UDP

receiver.js

// UDP: each datagram is handed over the moment it landsudp.on("message", (msg) => show(msg)); // TCP: bytes come out in order, so one gap holds up the resttcp.on("data", (chunk) => show(chunk));

game-client.js

let latest = 0;udp.on("message", (msg) => {  const { seq, state } = decode(msg);  // older than what's on screen, skip it  if (seq <= latest) return;  latest = seq;  draw(state);});

Topics

Next: How HTTP requests work

Open lesson