> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# UDP

> 使用 Bun 的 UDP API 实现具有高级实时需求的服务，如语音聊天

## 绑定 UDP 套接字 (`Bun.udpSocket()`)

要创建一个新的（已绑定的）UDP 套接字：

```ts theme={null}
const socket = await Bun.udpSocket({});
console.log(socket.port); // 由操作系统分配
```

指定一个端口：

```ts theme={null}
const socket = await Bun.udpSocket({
  port: 41234, // [!code ++]
});

console.log(socket.port); // 41234
```

### 发送数据报

指定要发送的数据、目标端口和目标地址。

```ts theme={null}
socket.send("Hello, world!", 41234, "127.0.0.1");
```

地址必须是有效的 IP 地址。`send` 不执行 DNS 解析，因为它用于低延迟操作。

### 接收数据报

创建套接字时，添加一个 `data` 回调来处理传入的数据包：

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const server = await Bun.udpSocket({
  socket: {
    data(socket, buf, port, addr) {
      console.log(`来自 ${addr}:${port} 的消息：`);
      console.log(buf.toString());
    },
  },
});

const client = await Bun.udpSocket({});
client.send("Hello!", server.port, "127.0.0.1");
```

### 连接

UDP 没有连接的概念，但许多 UDP 通信（尤其是作为客户端时）只涉及一个对等方。在这种情况下，你可以将套接字连接到该对等方，这会为你发送的每个数据包设置目标地址，并限制传入的数据包只来自该对等方。

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const server = await Bun.udpSocket({
  socket: {
    data(socket, buf, port, addr) {
      console.log(`来自 ${addr}:${port} 的消息：`);
      console.log(buf.toString());
    },
  },
});

const client = await Bun.udpSocket({
  connect: {
    port: server.port,
    hostname: "127.0.0.1",
  },
});

client.send("Hello");
```

连接是在操作系统级别实现的，因此它们也可以提高性能。

### 使用 `sendMany()` 一次发送多个数据包

要一次发送大量数据包而无需每次调用系统调用，可以使用 `sendMany()` 进行批处理。

对于未连接的套接字，`sendMany` 接收一个数组作为其唯一参数。每三个数组元素描述一个数据包：要发送的数据、目标端口和目标地址。

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const socket = await Bun.udpSocket({});

// 在单个操作中向 127.0.0.1:41234 发送 'Hello'，向 1.1.1.1:53 发送 'foo'
socket.sendMany(["Hello", 41234, "127.0.0.1", "foo", 53, "1.1.1.1"]);
```

对于已连接的套接字，`sendMany` 接收一个数组，其中每个元素是要发送给对等方的数据。

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const socket = await Bun.udpSocket({
  connect: {
    port: 41234,
    hostname: "localhost",
  },
});

socket.sendMany(["foo", "bar", "baz"]);
```

`sendMany` 返回成功发送的数据包数量。与 `send` 一样，它只接受有效的 IP 地址作为目标，不执行 DNS 解析。

### 处理背压

你发送的数据包可能无法放入操作系统的数据包缓冲区。当以下情况发生时可检测到：

* `send` 返回 `false`
* `sendMany` 返回的数字小于你指定的数据包数量。在这种情况下，Bun 会在套接字再次可写时调用 `drain` 套接字处理器：

```ts theme={null}
const socket = await Bun.udpSocket({
  socket: {
    drain(socket) {
      // 继续发送数据
    },
  },
});
```

### 套接字选项

UDP 套接字支持设置各种套接字选项：

```ts theme={null}
const socket = await Bun.udpSocket({});

// 启用广播以向广播地址发送数据包
socket.setBroadcast(true);

// 设置传出数据包的 IP TTL（生存时间）
socket.setTTL(64);
```

### 多播

Bun 支持 UDP 套接字的多播操作。使用 `addMembership` 和 `dropMembership` 加入和离开多播组：

```ts theme={null}
const socket = await Bun.udpSocket({});

// 加入多播组
socket.addMembership("224.0.0.1");

// 使用特定接口加入
socket.addMembership("224.0.0.1", "192.168.1.100");

// 离开多播组
socket.dropMembership("224.0.0.1");
```

其他多播选项：

```ts theme={null}
// 设置多播数据包的 TTL（网络跳数）
socket.setMulticastTTL(2);

// 控制多播数据包是否回环到本地套接字
socket.setMulticastLoopback(true);

// 指定用于传出多播数据包的接口
socket.setMulticastInterface("192.168.1.100");
```

对于源特定多播 (SSM)，使用 `addSourceSpecificMembership` 和 `dropSourceSpecificMembership`：

```ts theme={null}
socket.addSourceSpecificMembership("10.0.0.1", "232.0.0.1");
socket.dropSourceSpecificMembership("10.0.0.1", "232.0.0.1");
```
