Day 17: UDP & sockets — write a tiny TCP server
UDP: when reliability isn't worth the cost
UDP sends packets ('datagrams') with no handshake, no ordering guarantee, and no retransmission — just fire and forget. That sounds worse than TCP, but for the right workload it's a feature: DNS queries (Day 18), video/voice calls, and game state updates all care more about low latency than about a guaranteed, ordered delivery of every single packet. A dropped video frame from one second ago is worthless anyway — retransmitting it would only add lag.
- TCP: ordered, reliable, connection-oriented, higher overhead
- UDP: unordered, unreliable, connectionless, minimal overhead
- Use TCP when correctness matters more than latency (most APIs, file transfer)
- Use UDP when latency matters more than occasional loss (DNS, real-time media, some gaming)
Sockets: the programming interface underneath all of this
A socket is the OS-level handle a program uses to send/receive over TCP or UDP — it's the concrete thing your fetch() or HTTP client is built on top of, several layers down.
const net = require('net');
const server = net.createServer((socket) => {
console.log('client connected');
socket.on('data', (data) => {
socket.write(`echo: ${data}`);
});
socket.on('end', () => console.log('client disconnected'));
});
server.listen(9000, () => console.log('TCP server on :9000'));Hands-on: build and test it
Run the server above, then connect with nc localhost 9000 (or telnet localhost 9000) from another terminal and type something. Watch the echo come back — you're now seeing raw TCP without any HTTP layered on top of it.
Key terms
- Datagram
- A single, self-contained UDP packet sent with no connection setup and no delivery guarantee.
- Socket
- The OS-level handle representing one end of a network connection, used by TCP and UDP alike.
Why is UDP a reasonable choice for a live video call, despite offering no delivery guarantee?