TCP and UDP sockets
Prerequisites: previous curriculum lessons on Node streams, HTTP, buffers and asynchronous errors. Local lab baseline: Node.js 22.16.0, Linux, ESM. Use a disposable directory. Static examples are not ByteMind interactive execution. Each example is independent; save the named files together and run node main.mjs. The author harness imposes a five-second process deadline.
How it works
TCP does not preserve write boundaries: a read may contain half a message or several messages. Define framing, such as a delimiter or a bounded length prefix. A TCP half-close ends one direction while the other can remain open if configured. UDP preserves datagram boundaries at the receiving API, but the application must handle missing, duplicated or reordered messages if they matter. Bind examples to 127.0.0.1 and port 0 so the OS selects a free local port. An inactivity timeout does not close a TCP socket by itself; handle it explicitly.
Read a bounded TCP message across arbitrary chunks
import net from 'node:net';import { once } from 'node:events';const server = net.createServer({allowHalfOpen:true}, socket => { let received = ''; socket.setEncoding('utf8'); socket.setTimeout(1500, () => socket.destroy()); socket.on('data', chunk => { received += chunk; if(received.length > 32) socket.destroy(); }); socket.on('end', () => socket.end(received.toUpperCase())); socket.on('error', () => socket.destroy());});server.listen(0,'127.0.0.1'); await once(server,'listening');try { const client = net.createConnection(server.address().port,'127.0.0.1'); client.setTimeout(1500, () => client.destroy(new Error('timeout'))); await once(client,'connect'); client.write('book'); client.end('s'); let reply=''; for await (const chunk of client) reply+=chunk; console.log(reply);} finally { await new Promise(resolve=>server.close(resolve)); }Expected output:
BOOKSThe server waits for end-of-stream rather than guessing chunk boundaries. This one-message protocol uses the half-close as its frame boundary.
Receive one local UDP datagram
import dgram from 'node:dgram';import { once } from 'node:events';const receiver=dgram.createSocket('udp4'); const sender=dgram.createSocket('udp4');receiver.bind(0,'127.0.0.1'); await once(receiver,'listening');sender.bind(0,'127.0.0.1'); await once(sender,'listening');const controller=new AbortController(); const timer=setTimeout(()=>controller.abort(),1500);try { const message=once(receiver,'message',{signal:controller.signal}); sender.send(Buffer.from('stock:3'),receiver.address().port,'127.0.0.1'); const [data]=await message; console.log(data.toString('utf8'));} finally { clearTimeout(timer); sender.close(); receiver.close(); }Expected output:
stock:3This is one successful loopback datagram, not evidence that UDP always delivers.
Common mistakes
Never treat one data event as one request. Accumulate and parse bounded frames, or use a protocol library. Do not treat successful UDP send completion as proof of delivery.
Practice
Change the two TCP writes to three fragments without changing the final message. Explain why the output remains the same. For UDP, explain what the sender could do if a reply never arrives.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TCP and UDP sockets — knowledge check
Apply the lesson to a fresh scenario and explain the resource or protocol boundary.
A TCP sender writes two strings. What may the receiver observe?
What does UDP send completion establish?
Why bind a lab server to port 0 on loopback?