Use Bun’s native TCP API to implement performance-sensitive systems like database clients, game servers, or anything that needs to communicate over TCP (instead of HTTP)
Bun’s TCP API is low-level, intended for library authors and advanced use cases.
Bun.listen({ hostname: "localhost", port: 8080, socket: { data(socket, data) {}, // message received from client open(socket) {}, // socket opened close(socket, error) {}, // socket closed drain(socket) {}, // socket ready for more data error(socket, error) {}, // error handler },});
An API designed for speed
In Bun, you declare one set of handlers per server instead of assigning callbacks to each socket, as with Node.js EventEmitters or the web-standard WebSocket API.
For performance-sensitive servers, assigning listeners to each socket can cause significant garbage collector pressure and increase memory usage. By contrast, Bun only allocates one handler function for each event and shares it among all sockets. This is a small optimization, but it adds up.
Attach contextual data to a socket in the open handler.
Bun.listen returns a server that conforms to the TCPSocketListener interface.
server.ts
const server = Bun.listen({ /* config*/});// stop listening// parameter determines whether active connections are closedserver.stop(true);// let Bun process exit even if server is still listeningserver.unref();
Use Bun.connect to connect to a TCP server. Specify the server with hostname and port. TCP clients can define the same set of handlers as Bun.listen, plus a few client-specific handlers.
Both TCP servers and sockets can be hot reloaded with new handlers.
const server = Bun.listen({ /* config */});// reloads handlers for all active server-side socketsserver.reload({ socket: { data() { // new 'data' handler }, },});
To buffer writes, use Bun’s ArrayBufferSink with the {stream: true} option:
server.ts
import { ArrayBufferSink } from "bun";const sink = new ArrayBufferSink();sink.start({ stream: true, highWaterMark: 1024,});sink.write("h");sink.write("e");sink.write("l");sink.write("l");sink.write("o");queueMicrotask(() => { const data = sink.flush(); const wrote = socket.write(data); if (wrote < data.byteLength) { // put it back in the sink if the socket is full sink.write(data.subarray(wrote)); }});
CorkingSupport for corking is planned, but in the meantime backpressure must be managed manually with the drain handler.