net.createServer() and UDP datagram boundaries
TCP provides an ordered, reliable byte stream between connected endpoints; UDP sends individual datagrams without guaranteeing delivery or ordering. Node exposes TCP through `node:net` and UDP through `node:dgram`. Choose the transport according to the application contract, not the assumption that one is always faster. 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. 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. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/net.html, https://nodejs.org/download/release/v22.16.0/docs/api/dgram.html.
Formal Syntax & Structure
net.createServer([options][, connectionListener]); dgram.createSocket(type[, callback])Working Example
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)); }