Sending and Receiving UDP Messages with Bun.udpSocket
In Bun, you create a socket with Bun.udpSocket, send a message with send, and receive messages in the data handler written in the socket option. It is built into Bun, so no package is needed.
UDP is the protocol you use when you want to send small messages quickly without setting up a connection, such as voice chat, game position updates, or sending logs and metrics. In my test environment, I ran a server that echoes back whatever text it receives and a client that sends to it, both on the same VM. I checked what actually happens with message boundaries, when no one is listening, connect, and the maximum message size.
The test environment was Ubuntu 24.04 with Bun 1.4.4. The server and client ran on the same VM, using port 41234 on 127.0.0.1. The code is written in TypeScript and also passes a tsc --strict type check. I did not test IPv6, broadcast, multicast, large volumes of sends that cause drain to be called, Windows or macOS, or communication between separate machines.
- 1. Creating an echo server with Bun.udpSocket
- 2. Three sends arrive as three data calls
- 3. Pass the destination as an IP address
- 4. send returns true even when no one is listening
- 5. With connect, messages from others are not delivered
- 6. The largest message sent over loopback was 65,507 bytes
- 7. A second socket on the same port raises EADDRINUSE
Creating an echo server with Bun.udpSocket
Passing port to Bun.udpSocket creates a socket that receives on that port. If you omit port, the OS picks a free port (official docs, section on creating a socket). The return value is a Promise, so you await it.
Received messages are delivered to the data handler passed in socket. The arguments are the socket, the data, the sender's port, and the sender's address, in that order (official docs, section on receiving). The type definitions show a fifth argument, flags. flags.truncated tells you whether the received data was cut off because it did not fit in the receive buffer (ReceiveFlags in the type definitions).
// server.ts
const server = await Bun.udpSocket({
hostname: "127.0.0.1",
port: 41234,
socket: {
data(socket, buf, port, addr, flags) {
const text = buf.toString();
console.log(`[server] from ${addr}:${port} ${JSON.stringify(text)} (${buf.constructor.name}, ${buf.byteLength} bytes, truncated=${flags.truncated})`);
socket.send(`echo: ${text}`, port, addr);
},
},
});
console.log(`[server] bound ${server.hostname}:${server.port}`);
UDP has no connection, so the reply is sent with send to the sender's port and address that arrived in data. send takes the data to send, the destination port, and the destination address (official docs, section on sending).
The client is also created with Bun.udpSocket. This one does not specify port, and it calls close once it receives a reply.
// client.ts
const client = await Bun.udpSocket({
socket: {
data(socket, buf, port, addr) {
console.log(`[client] from ${addr}:${port} ${JSON.stringify(buf.toString())}`);
socket.close();
},
},
});
console.log(`[client] bound ${client.hostname}:${client.port}`);
const ok = client.send("hello", 41234, "127.0.0.1");
console.log(`[client] send returned ${ok}`);
I started the server in the background with bun server.ts, then ran bun client.ts twice.
$ bun client.ts
[client] bound 0.0.0.0:50207
[client] send returned true
[client] from 127.0.0.1:41234 "echo: hello"
$ bun client.ts
[client] bound 0.0.0.0:37756
[client] send returned true
[client] from 127.0.0.1:41234 "echo: hello"
The server printed the following.
[server] bound 127.0.0.1:41234
[server] from 127.0.0.1:50207 "hello" (Buffer, 5 bytes, truncated=false)
[server] from 127.0.0.1:37756 "hello" (Buffer, 5 bytes, truncated=false)
The client port was a different number each run, chosen by the OS (50207, then 37756). The server's data handler received that number as the sender's port. The data arrives as a Buffer, so convert it with toString() if you want to handle it as text.
If you do not call close, the socket stays open and the process does not exit. I ran a client that only printed the reply and did not call close, with timeout 3 attached. It kept running after printing the reply and was stopped by timeout after 3 seconds (exit code 124).
Three sends arrive as three data calls
To check whether the data from one send arrives as one message (a datagram), I sent three times in a row from the client.
// client-three.ts
const client = await Bun.udpSocket({
socket: {
data(socket, buf) {
console.log(`[client] data: ${JSON.stringify(buf.toString())}`);
},
},
});
client.send("one", 41234, "127.0.0.1");
client.send("two", 41234, "127.0.0.1");
client.send("three", 41234, "127.0.0.1");
await Bun.sleep(200);
client.close();
$ bun client-three.ts
[client] data: "echo: one"
[client] data: "echo: two"
[client] data: "echo: three"
[server] from 127.0.0.1:41044 "one" (Buffer, 3 bytes, truncated=false)
[server] from 127.0.0.1:41044 "two" (Buffer, 3 bytes, truncated=false)
[server] from 127.0.0.1:41044 "three" (Buffer, 5 bytes, truncated=false)
The server's data handler was called three times, and each call received one message. You do not need a newline or other delimiter to mark message boundaries. Each call to data gives you one complete message.
You can send the same three messages in one call with sendMany. On a socket with no fixed destination, you pass a single array with the data, port, and address listed in groups of three (official docs, section on sendMany).
const sent = client.sendMany([
"a", 41234, "127.0.0.1",
"b", 41234, "127.0.0.1",
"c", 41234, "127.0.0.1",
]);
sendMany returns the number of messages sent, which was 3 here. The server received "a", "b", and "c" as three separate messages.
Pass the destination as an IP address
Pass an IP address as the destination of send. send does not resolve host names through DNS (official docs, section on sending). When I passed "localhost" as the destination, send threw an exception immediately.
$ bun client-nodns.ts
[client] catch: TypeError ERR_INVALID_ARG_TYPE Invalid address
If you only know the host name of the destination, look up its IP address first and then pass that to send.
send returns true even when no one is listening
I ran the client without starting the server, and send still returned true. send returns false when the data could not be put into the OS buffer (official docs, section on backpressure). The return value of send does not tell you whether the message reached the other side.
This is the output when I sent to a port with no listener, without writing an error handler.
$ bun client-noserver-nohandler.ts
[client] send returned true
ECONNREFUSED: connection refused, recv
syscall: "recv",
errno: -111,
errqueue: true,
code: "ECONNREFUSED"
[client] no reply in 300ms
Bun v1.4.4 (Linux x64)
After sending, an ECONNREFUSED error was printed. The "no reply" message appeared after waiting 300 ms, but the process ended with exit code 1.
With an error handler in place, the process did not exit with code 1 because of this error. However, in the test environment with Bun 1.4.4, the error handler received only one argument, the socket, and the second argument was undefined. The SocketHandler type definition declares the second argument as error: Error. In the test environment, I could not use the code of the error in the error handler to branch the handling.
So I wrote a function that sets a time limit for the reply and treats the request as failed if no reply arrives within that time.
// client-request.ts
// Send one message and wait for a reply. If no reply arrives in time, give up and throw.
async function request(text: string, timeoutMs: number): Promise<string> {
const { promise, resolve, reject } = Promise.withResolvers<string>();
const socket = await Bun.udpSocket({
socket: {
data(socket, buf) {
resolve(buf.toString());
},
error(socket, error) {
console.log(`[client] error handler called: error = ${error}`);
},
},
});
const timer = setTimeout(() => reject(new Error(`no reply in ${timeoutMs}ms`)), timeoutMs);
socket.send(text, 41234, "127.0.0.1");
try {
return await promise;
} finally {
clearTimeout(timer);
socket.close();
}
}
const start = performance.now();
try {
const reply = await request("hello", 500);
console.log(`[client] reply: ${JSON.stringify(reply)} (${Math.round(performance.now() - start)}ms)`);
} catch (error) {
console.log(`[client] ${(error as Error).message} (${Math.round(performance.now() - start)}ms)`);
}
Here are the results with the server stopped and with the server running.
$ bun client-request.ts
[client] error handler called: error = undefined
[client] no reply in 500ms (502ms)
$ bun client-request.ts
[client] reply: "echo: hello" (2ms)
When no server was running, the error handler was called, and then after 500 ms the function threw a no reply exception. In both cases the exit code was 0. The socket is closed in finally, so the process ended there.
With connect, messages from others are not delivered
When there is exactly one peer to communicate with, pass connect to Bun.udpSocket. The destination is then fixed, so send only needs the data, and the socket receives only messages from that peer (official docs, section on connect).
I also sent directly to the port of the connected client from a separate socket (other).
// client-connected.ts
const client = await Bun.udpSocket({
connect: { hostname: "127.0.0.1", port: 41234 },
socket: {
data(socket, buf, port, addr) {
console.log(`[client] from ${addr}:${port} ${JSON.stringify(buf.toString())}`);
},
},
});
console.log(`[client] remoteAddress: ${JSON.stringify(client.remoteAddress)}`);
console.log(`[client] send returned ${client.send("hello")}`);
// Send directly from a different socket to this client's port
const other = await Bun.udpSocket({
socket: {
error() {
console.log("[other] error handler called");
},
},
});
console.log(`[other] send returned ${other.send("from other", client.port, "127.0.0.1")}`);
await Bun.sleep(300);
client.close();
other.close();
$ bun client-connected.ts
[client] remoteAddress: {"address":"127.0.0.1","family":"IPv4","port":41234}
[client] send returned true
[other] send returned true
[other] error handler called
[client] from 127.0.0.1:41234 "echo: hello"
The client received only the reply from the server. The "from other" message sent by other never arrived. On the other side, the error handler was called, just as when sending to a port with no listener.
I then removed connect and used the same client with the destination passed to send. In that version, "from other" was delivered as well. These are the two lines the client received.
[client] from 127.0.0.1:41872 "from other"
[client] from 127.0.0.1:41234 "echo: hello"
A socket without connect accepts messages from anyone who knows its port. On the receiving side, either check the sender's address and port in data, or fix the peer with connect. The request function in the previous section does not check the sender, to keep the example simple.
The largest message sent over loopback was 65,507 bytes
On IPv4 loopback (127.0.0.1) in the test environment, I called send with a Uint8Array filled with zeros, changing its size each time.
$ bun client-size.ts
[client] 1000 bytes: send returned true
[client] 65507 bytes: send returned true
[client] 65508 bytes: catch EMSGSIZE EMSGSIZE: message too long, send
[client] error handler called
[server] received 1000 bytes (truncated=false)
[server] received 65507 bytes (truncated=false)
Messages up to 65,507 bytes arrived as one message, and truncated was false. At 65,508 bytes, send threw an EMSGSIZE exception immediately, and then the error handler was called. Nothing arrived at the server.
A second socket on the same port raises EADDRINUSE
When I tried to create a second socket on the same port, await Bun.udpSocket(...) threw an EADDRINUSE exception.
$ bun bind-twice.ts
[first] bound 41234
[second] catch: Error EADDRINUSE bind EADDRINUSE 127.0.0.1
For a server that listens on a fixed port, you can catch this exception with try/catch and print a message saying the port is already in use before exiting.





