日本語

How to Create a TCP Server and Client with Bun

​​Bun​Networking,TCP,TypeScript

In Bun, passing a socket handler object to Bun.listen creates a TCP server, and passing a handler object of the same shape to Bun.connect creates a client. Both are built into Bun, so no packages are required.

Use them when you write TCP communication with your own protocol instead of HTTP, such as chat or game servers and database clients. In my test environment, I ran the server and client in the same VM and checked what actually happens with message delimiting, connection failures, how to stop the server, and how to send large data.

Note

The test environment is Ubuntu 24.04 and Bun 1.4.4. The server and client ran in the same VM and connected to port 9000 on 127.0.0.1. The code is written in TypeScript and also passes tsc --strict type checking. I did not test TLS (the tls option), Unix domain sockets, replacing handlers with reload, Windows or macOS, or communication between separate machines.

Creating a Server That Echoes Received Text with Bun.listen

Bun.listen takes the address to listen on (hostname), the port (port), and a socket handler object. You write the handlers once for the server, not once per connection (official docs: section on starting a server, official docs: how handlers are held). To tell which connection an event belongs to, use the first argument, socket.

Store values you want per connection in socket.data. If you pass a type, as in Bun.listen<Conn>, socket.data gets that type (official docs: socket.data example).

ts
// server.ts
type Conn = { id: number };
let nextId = 1;

const server = Bun.listen<Conn>({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    open(socket) {
      socket.data = { id: nextId++ };
      console.log(`[server] open #${socket.data.id} from ${socket.remoteAddress}`);
    },
    data(socket, data) {
      const text = data.toString();
      console.log(`[server] data #${socket.data.id}: ${JSON.stringify(text)} (${data.constructor.name}, ${data.byteLength} bytes)`);
      socket.write(`echo: ${text}`);
    },
    close(socket, error) {
      console.log(`[server] close #${socket.data.id}`, error ?? "");
    },
    error(socket, error) {
      console.log(`[server] error #${socket.data.id}`, error);
    },
  },
});

console.log(`[server] listening on ${server.hostname}:${server.port}`);

You create a client with Bun.connect. Awaiting the returned Promise gives you a connected socket (official docs: section on creating a connection).

ts
// client.ts
const socket = await Bun.connect({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    open() {
      console.log("[client] open");
    },
    data(socket, data) {
      console.log(`[client] data: ${JSON.stringify(data.toString())}`);
      socket.end();
    },
    end() {
      console.log("[client] end");
    },
    close() {
      console.log("[client] close");
    },
  },
});

const written = socket.write("hello\n");
console.log(`[client] write returned ${written}`);

I started bun server.ts in the background and ran bun client.ts twice. Here is the output of the first run (the second run was the same).

text
$ bun client.ts
[client] open
[client] write returned 6
[client] data: "echo: hello\n"
[client] close

On the server side, the output was:

text
[server] listening on 127.0.0.1:9000
[server] open #1 from 127.0.0.1
[server] data #1: "hello\n" (Buffer, 6 bytes)
[server] close #1 
[server] open #2 from 127.0.0.1
[server] data #2: "hello\n" (Buffer, 6 bytes)
[server] close #2 

The data handler receives a Buffer, not a string. To treat it as text, convert it with toString(). If you want a type other than Buffer, set binaryType to "arraybuffer" or "uint8array" (type definitions: binaryType, list of available types). The connection numbers #1 and #2 differ, which also shows that socket.data is separate for each connection.

The client's end was not called here. end is the handler called when the other side sends the end of its transmission (a TCP FIN) (type definitions: end). When the client closes the connection itself with socket.end(), as this client does, end is not called. Only close was called.

Three writes can arrive in a single data call

In TCP, the number of write calls does not match the number of times the other side's data handler is called. When the client called write three times in a row, the server's data handler was called only once.

ts
// client-three.ts
const socket = await Bun.connect({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    data(socket, data) {
      console.log(`[client] data: ${JSON.stringify(data.toString())}`);
    },
  },
});

socket.write("one\n");
socket.write("two\n");
socket.write("three\n");
setTimeout(() => socket.end(), 200);
text
$ bun client-three.ts
[client] data: "echo: one\ntwo\nthree\n"
text
[server] data #1: "one\ntwo\nthree\n" (Buffer, 14 bytes)

A single data call delivered the 14 bytes of three lines, and the server returned them in one write. The reverse can also happen: one write can be split across several data calls. Later in this article, when I sent 32 MB in one write, the server's data handler was called 18 times. So don't treat one data call as one message. Instead, decide in your protocol where messages end.

Here I treated everything up to a newline as one message. The server converts the received data to a string, accumulates it in socket.data.buffer, and splits it at each newline.

ts
// server-lines.ts
type Conn = { buffer: string };

Bun.listen<Conn>({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    open(socket) {
      socket.data = { buffer: "" };
    },
    data(socket, data) {
      console.log(`[server] data: ${JSON.stringify(data.toString())}`);
      socket.data.buffer += data.toString();
      const lines = socket.data.buffer.split("\n");
      socket.data.buffer = lines.pop()!; // the remainder that does not end with a newline
      for (const line of lines) {
        console.log(`[server] line: ${JSON.stringify(line)}`);
        socket.write(`echo: ${line}\n`);
      }
    },
  },
});

Connecting with the same client-three.ts, the server took three lines out of one data call and returned them one at a time.

text
$ bun client-three.ts
[client] data: "echo: one\necho: two\necho: three\n"
text
[server] data: "one\ntwo\nthree\n"
[server] line: "one"
[server] line: "two"
[server] line: "three"

I also tried a client that splits one line into "hel" and "lo\n" and sends them 100 ms apart. data was called twice, and the second call, which brought the newline, completed the line "hello".

text
[server] data: "hel"
[server] data: "lo\n"
[server] line: "hello"

In this example, each data chunk is converted to a string with toString() before being accumulated. With this approach, when a character that takes multiple bytes, such as a Japanese character, is split across data calls, it gets garbled. I sent the UTF-8 bytes of the Japanese word "neko" (cat), followed by a newline, and split the data after the second byte of its first character, which is three bytes long. The result was as follows:

text
[server] data: "�"
[server] data: "�こ\n"
[server] line: "��こ"

If you create one TextDecoder per connection, store it in socket.data, and convert with decode(data, { stream: true }) instead of toString(), the garbling does not happen. stream is an option you set to true when you decode data in several chunks, one after another (MDN: TextDecoder.decode).

ts
// server-lines-decoder.ts (only the parts changed from server-lines.ts)
type Conn = { buffer: string; decoder: TextDecoder };

    open(socket) {
      socket.data = { buffer: "", decoder: new TextDecoder() };
    },
    data(socket, data) {
      const text = socket.data.decoder.decode(data, { stream: true });
      // From here down, same as server-lines.ts except data.toString() is replaced with text
text
[server] data: ""
[server] data: "ねこ\n"
[server] line: "ねこ"

The 2 bytes received in the first data call became an empty string. In the second decode call, they were combined with the carried-over bytes, and the two characters (neko, "cat") were complete.

When the Server Is Not Running, await Throws an Error

When I ran the client without starting the server, the Promise from Bun.connect was rejected, and the process stopped with exit code 1.

text
$ bun client-refused-nohandler.ts
error: Failed to connect
 syscall: "connect",
   errno: -111,
    code: "ECONNREFUSED"


Bun v1.4.4 (Linux x64)

The client also has a connectError handler, which is called when the connection fails. However, even with connectError written, await Bun.connect(...) still threw an exception. After connectError was called, the same error appeared, and the process stopped with exit code 1.

text
$ bun client-refused-handler-only.ts
[client] connectError: Failed to connect
error: Failed to connect
 syscall: "connect",
   errno: -111,
    code: "ECONNREFUSED"


Bun v1.4.4 (Linux x64)

The type definitions also say that the Promise from Bun.connect is rejected after connectError is called (type definitions: connectError). The same description says that if you write connectError, this rejection is no longer reported as an unhandled rejection. Even so, when you await it, it throws and stops as shown above, so catch it with try/catch.

ts
// client-refused.ts
try {
  await Bun.connect({
    hostname: "127.0.0.1",
    port: 9000,
    socket: {
      data() {},
      connectError(socket, error) {
        console.log(`[client] connectError: ${error.message}`);
      },
    },
  });
} catch (error) {
  const e = error as Error & { code?: string };
  console.log(`[client] catch: ${e.name} ${e.code} ${e.message}`);
}
text
$ bun client-refused.ts
[client] connectError: Failed to connect
[client] catch: Error ECONNREFUSED Failed to connect

The exit code was 0. The reason the connection failed can be identified from the error's code (here, ECONNREFUSED).

How the Argument to server.stop() Changes Whether Active Connections Close

stop() on the server returned by Bun.listen stops accepting new connections. If you pass true, it also closes the connections that are currently open (official docs: TCPSocketListener example).

I made a server that calls stop() 100 ms after accepting a connection. From the client, I sent one line 300 ms after connecting, and then also tried a new connection. The times in the output are elapsed time since the client started connecting.

ts
// server-stop.ts (start it with the value to pass to stop, e.g. bun server-stop.ts true)
const closeActive = Bun.argv[2] === "true";

const server = Bun.listen({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    open() {
      console.log("[server] open");
      setTimeout(() => {
        server.stop(closeActive);
        console.log(`[server] stop(${closeActive}) called`);
      }, 100);
    },
    data(socket, data) {
      socket.write(`echo: ${data}`);
    },
    close() {
      console.log("[server] close");
    },
  },
});
ts
// client-stop.ts
const start = performance.now();
const t = () => `${Math.round(performance.now() - start)}ms`;

const socket = await Bun.connect({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    data(socket, data) {
      console.log(`[client] ${t()} data: ${JSON.stringify(data.toString())}`);
      socket.end();
    },
    end() {
      console.log(`[client] ${t()} end`);
    },
    close() {
      console.log(`[client] ${t()} close`);
    },
  },
});

await Bun.sleep(300);
console.log(`[client] ${t()} write returned ${socket.write("hello\n")}`);
await Bun.sleep(100);

try {
  await Bun.connect({ hostname: "127.0.0.1", port: 9000, socket: { data() {} } });
  console.log(`[client] ${t()} new connection: ok`);
} catch (error) {
  console.log(`[client] ${t()} new connection: ${(error as { code?: string }).code}`);
}

Client output with stop(false):

text
$ bun client-stop.ts
[client] 301ms write returned 6
[client] 302ms data: "echo: hello\n"
[client] 302ms close
[client] 402ms new connection: ECONNREFUSED

The server calls stop(false) 100 ms after accepting the connection, but the connection that was already open kept working, and the line sent at 300 ms got a reply. The new connection was refused with ECONNREFUSED.

With stop(true), the output was:

text
$ bun client-stop.ts
[client] 101ms end
[client] 102ms close
[client] 301ms write returned -1
[client] 401ms new connection: ECONNREFUSED

At 100 ms the server closed the connection, and on the client, end and close were called. The write after that returned -1. According to the type definitions, write returns -1 when the socket is closed or closing (type definitions: write).

When I checked after the client finished, the server process had exited on its own in both cases.

Send Large Data While Checking the Return Value of write

write returns the number of bytes it sent. If it could not send everything, it returns a number smaller than the size you passed (same type definitions: write). The official docs also say that Bun's TCP sockets do not buffer the outgoing data internally (official docs: buffering section).

I connected a client that sends 32 MB (33,554,432 bytes) in a single write and calls end without checking the return value, to a server that only counts received bytes. The server received 7,515,399 bytes on the first run and 5,158,011 bytes on the second. Both are less than a quarter of the total. No error was shown, and the client exited with code 0.

ts
// client-big-ignore.ts (bad example: ignores the return value)
const payload = new Uint8Array(32 * 1024 * 1024);

await Bun.connect({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    open(socket) {
      socket.write(payload);
      socket.end();
    },
    data() {},
  },
});
text
[server] received 7515399 bytes in 18 data calls

To send everything, advance the position by the number of bytes write returned, and send the rest when drain is called, which happens when the socket can accept more data again (official docs: list of handlers).

ts
// client-big.ts
const payload = new Uint8Array(32 * 1024 * 1024);
let offset = 0;
let drains = 0;

function flush(socket: Bun.Socket) {
  while (offset < payload.byteLength) {
    const wrote = socket.write(payload.subarray(offset));
    if (wrote <= 0) return; // buffer is full, so wait for drain
    if (offset === 0) console.log(`[client] first write: ${wrote} / ${payload.byteLength} bytes`);
    offset += wrote;
  }
  console.log(`[client] all ${offset} bytes written (drain called ${drains} times)`);
  socket.end();
}

await Bun.connect({
  hostname: "127.0.0.1",
  port: 9000,
  socket: {
    open(socket) {
      flush(socket);
    },
    drain(socket) {
      drains++;
      flush(socket);
    },
    data() {},
  },
});

Results of three runs:

Run Bytes sent by the first write Number of drain calls Bytes received by the server
1 4,830,596 13 33,554,432
2 4,896,079 11 33,554,432
3 4,961,562 13 33,554,432

The amount the first write could send and the number of drain calls were not constant, but all 32 MB arrived in all three runs.

Warning

The second argument to write can take the byte offset where sending starts (byteOffset). According to the type definitions, if you omit the third argument, it means "everything from that position to the end." However, in my test environment, when I wrote socket.write(payload, offset), the second write call failed with RangeError: The value of "byteLength" is out of range. It must be >= 0 and <= 28176032. Received 33554432 and the process stopped. The byteLength used was the full length (33,554,432), not the remaining length. The code passes type checking, so you won't notice until you run it. When I sliced with subarray(offset) and passed that, as in the code above, this error did not occur.

​Posted by 86