# net WebSocket 通信

## 功能

`net.listen({type: 'ws'})` 启动 WebSocket 服务端，`net.connect({type: 'ws'})` 创建 WebSocket 客户端。

## 服务端语法

```bt
server = net.listen({
    type: 'ws',
    bind: '127.0.0.1:9002',
    route: '/ws',
    on_connect: fn(socket) {},
    on_message: fn(socket, message) {},
    on_close: fn(socket) {},
    on_error: fn(message) {}
})
```

## 客户端语法

```bt
socket = net.connect({type: 'ws', url: 'ws://127.0.0.1:9002/ws'})
socket.on_message(fn(message) {})
socket.on_close(fn() {})
socket.on_error(fn(message) {})
socket.send('hello')
socket.close()
```

## 服务端配置字段

`net.listen({type: 'ws', ...})` 使用以下字段：

| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|------|------|
| type | String | 是 | 无 | 固定为 `ws`。 |
| bind | String | 是 | 无 | WebSocket 服务端监听地址，格式为 `主机:端口`，例如 `127.0.0.1:9002`。端口写 `0` 时由系统分配空闲端口。 |
| route | String | 否 | `/ws` | WebSocket 握手路径。客户端 URL 路径必须与该值一致。 |
| on_connect | Fn | 否 | 无 | 客户端连接成功时调用，回调参数为 `socket`。 |
| on_message | Fn | 否 | 无 | 收到客户端文本消息时调用，回调参数为 `socket, message`。 |
| on_close | Fn | 否 | 无 | 客户端连接关闭时调用，回调参数为 `socket`。 |
| on_error | Fn | 否 | 无 | 服务端或连接处理错误时调用，回调参数为 `message`。 |

## 客户端配置字段

`net.connect({type: 'ws', ...})` 使用以下字段：

| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|------|------|
| type | String | 是 | 无 | 固定为 `ws`。 |
| url | String | 是 | 无 | WebSocket 完整连接地址，例如 `ws://127.0.0.1:9002/ws`。 |

## 返回值

| 类型 | 说明 |
|------|------|
| WsServer | `net.listen({type:'ws'})` 返回的 WebSocket 服务端句柄。 |
| WsSocket | WebSocket 连接句柄。服务端回调中的 socket 和客户端 `net.connect({type:'ws'})` 返回值都使用该类型。 |

## WsServer 字段和方法

| 名称 | 类型 | 说明 |
|------|------|------|
| addr | String | 实际监听地址，格式通常为 `host:port`；bind 端口为 0 时可从这里读取系统分配后的端口。 |
| type | String | 固定为 `ws`。 |
| close() | Fn -> Bool | 关闭 WebSocket 服务端监听，成功返回 true。 |

## WsSocket 字段和方法

| 名称 | 类型 | 说明 |
|------|------|------|
| addr | String | WebSocket 对端地址或连接目标地址，格式通常为 `host:port`。 |
| type | String | 固定为 `ws`。 |
| send(data) | Fn -> Bool | 发送 WebSocket 文本消息，成功返回 true。 |
| write(data) | Fn -> Bool | `send(data)` 的同义方法。 |
| close() | Fn -> Bool | 关闭 WebSocket 连接，成功返回 true。 |
| on_message(fn(message) {}) | Fn -> WsSocket | 客户端连接句柄注册消息回调。 |
| on_close(fn() {}) | Fn -> WsSocket | 客户端连接句柄注册关闭回调。 |
| on_error(fn(message) {}) | Fn -> WsSocket | 客户端连接句柄注册错误回调。 |

## 服务端回调参数

| 回调 | 参数 | 说明 |
|------|------|------|
| on_connect | socket: WsSocket | 新客户端连接成功时触发。 |
| on_message | socket: WsSocket, message: String | 收到客户端文本消息时触发。 |
| on_close | socket: WsSocket | 客户端连接关闭时触发。 |
| on_error | message: String | 服务端或连接处理错误时触发。 |

## 示例

```bt
// 监听本机随机空闲端口，并限定 WebSocket 路径为 /ws。
server = net.listen({
    type: 'ws',
    bind: '127.0.0.1:0',
    route: '/ws'
})

result = server.type
server.close()

// 输出：ws
print result
```

## 注意事项

- 服务端 route 默认 /ws。
- WebSocket read() 不支持同步读取；消息通过后台事件回调分发。
