Skip to main content
Bun’s TCP API is low-level, intended for library authors and advanced use cases.

Start a server (Bun.listen())

Start a TCP server with Bun.listen:
server.ts
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.
server.ts
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.
server.ts
To enable TLS, pass a tls object containing key and cert fields.
server.ts
The key and cert fields expect the contents of your TLS key and certificate. This can be a string, BunFile, TypedArray, or Buffer.
server.ts
Bun.listen returns a server that conforms to the TCPSocketListener interface.
server.ts

Create a connection (Bun.connect())

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.
server.ts
To require TLS, specify tls: true.

Hot reloading

Both TCP servers and sockets can be hot reloaded with new handlers.

Buffering

TCP sockets in Bun do not buffer data, so performance-sensitive code should buffer writes itself. For example, this:
…performs significantly worse than this:
To buffer writes, use Bun’s ArrayBufferSink with the {stream: true} option:
server.ts
CorkingSupport for corking is planned, but in the meantime backpressure must be managed manually with the drain handler.