new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Runtime · all subjects

tcp sockets

15 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

TCP socket APIs

Bun provides Bun.listen() to start a TCP server and Bun.connect() to create a TCP connection.

node:net fully implemented

node:net is fully implemented in Bun, including BlockList, SocketAddress, autoSelectFamily, Unix domain sockets and server.listen({ fd }). new net.Socket({ fd }) cannot read from an existing file descriptor (only write-only wrapping works). server.listen(handle) only accepts { fd }. Missing blockList.toJSON()/fromJSON().

Bun.listen() - TCP server parameters

Bun.listen() creates a TCP server. It takes a configuration object with properties: hostname (server address), port (server port), socket (object containing event handlers), and optional tls (object with key and cert for TLS). The socket object contains event handlers: data(socket, data) for messages from clients, open(socket) when socket opens, close(socket, error) when socket closes, drain(socket) when socket is ready for more data, and error(socket, error) for error handling.

Bun.listen() returns TCPSocketListener

Bun.listen() returns a server object conforming to the TCPSocketListener interface. This server object has two methods: stop(boolean) to stop listening (the boolean parameter determines whether active connections are closed), and unref() to allow the Bun process to exit even if the server is still listening.

TCP socket handlers in Bun.listen()

Bun.listen() socket handlers are: 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. All handlers are shared among all sockets connected to the server for performance optimization.

Attaching contextual data to TCP sockets

You can attach contextual data to a TCP socket by assigning to socket.data in the open handler. Use a generic type parameter on Bun.listen<SocketData>() to specify the shape of the data. The data is then accessible in other handlers via socket.data.

TLS/SSL configuration in Bun.listen()

To enable TLS in Bun.listen(), pass a tls object with key and cert fields containing the TLS certificate and private key contents. The key and cert can be a string, BunFile, TypedArray, Buffer, or an array of these types. Example: tls: { key: Bun.file('./key.pem'), cert: Bun.file('./cert.pem') }.

Bun.connect() - TCP client connection

Bun.connect() creates a TCP client connection. It takes a configuration object with properties: hostname and port to specify the server address, and socket (object containing event handlers). It returns a promise that resolves to a socket object. The socket object has standard handlers (data, open, close, drain, error) plus client-specific handlers: connectError(socket, error) when connection fails, end(socket) when server closes the connection, and timeout(socket) when connection times out.

TCP client socket handlers in Bun.connect()

Bun.connect() supports handlers: data(socket, data), open(socket), close(socket, error), drain(socket), error(socket, error) shared with Bun.listen(), plus client-specific handlers: connectError(socket, error) - connection failed, end(socket) - connection closed by server, timeout(socket) - connection timed out.

TLS in Bun.connect() for TCP clients

To require TLS when connecting as a TCP client with Bun.connect(), specify tls: true in the configuration object.

Hot reloading TCP client socket handlers

Call socket.reload({ handler_name() { /* new handler */ } }) on a TCP client socket to reload handlers without closing the connection.

TCP socket buffering in Bun

TCP sockets in Bun do not buffer data automatically. Multiple small writes like socket.write('h'); socket.write('e') perform significantly worse than a single write socket.write('hello'). For performance-sensitive code, manually buffer writes using ArrayBufferSink with {stream: true} option.

ArrayBufferSink for buffering TCP writes

Use ArrayBufferSink from the 'bun' module to buffer TCP socket writes. Create a new sink with new ArrayBufferSink(), call sink.start({ stream: true, highWaterMark: 1024 }), write data with sink.write(), and flush with sink.flush() to get a buffer to pass to socket.write(). Check socket.write() return value to handle backpressure: if fewer bytes were written than the buffer size, put the remaining data back in the sink.

ArrayBufferSink example for TCP buffering

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) { sink.write(data.subarray(wrote)); } });

TCP backpressure handling with drain handler

In Bun TCP sockets, when buffering writes with ArrayBufferSink, you must manage backpressure manually using the drain handler, which fires when the socket is ready for more data. Corking support is planned but not yet available.

Give your agent this brain