Skip to content

WebSocket

WebSocket 是一种用于客户端和服务器之间通信的实时协议。

¥WebSocket is a realtime protocol for communication between your client and server.

与 HTTP 不同,HTTP 中客户端需要反复向网站请求信息并等待回复,而 WebSocket 则建立了一条直接的通信线路,客户端和服务器可以直接来回发送消息,使对话更快捷、更顺畅,无需重新发送每条消息。

¥Unlike HTTP where our client repeatedly asks the website for information and waits for a reply each time, WebSocket sets up a direct line where our client and server can send messages back and forth directly, making the conversation quicker and smoother without having to start over with each message.

SocketIO 是一个流行的 WebSocket 库,但它并非唯一的库。Elysia 使用 Bun 在底层使用 uWebSocket 并使用相同的 API。

¥SocketIO is a popular library for WebSocket, but it is not the only one. Elysia uses uWebSocket which Bun uses under the hood with the same API.

要使用 WebSocket,只需调用 Elysia.ws()

¥To use WebSocket, simply call Elysia.ws():

typescript
import { Elysia } from 'elysia'

new Elysia()
    .ws('/ws', {
        message(ws, message) {
            ws.send(message)
        }
    })
    .listen(3000)

WebSocket 消息验证:

¥WebSocket message validation:

与普通路由相同,WebSocket 也接受一个 schema 对象来严格定义请求的类型并进行验证。

¥Same as normal routes, WebSockets also accept a schema object to strictly type and validate requests.

typescript
import { Elysia, t } from 'elysia'

const app = new Elysia()
    .ws('/ws', {
        // validate incoming message
        body: t.Object({
            message: t.String()
        }),
        query: t.Object({
            id: t.String()
        }),
        message(ws, { message }) {
            // Get schema from `ws.data`
            const { id } = ws.data.query
            ws.send({
                id,
                message,
                time: Date.now()
            })
        }
    })
    .listen(3000)

WebSocket 模式可以验证以下内容:

¥WebSocket schema can validate the following:

  • message - 一条传入消息。

  • query - 查询字符串或 URL 参数。

  • params - 路径参数。

  • header - 请求的标头。

  • cookie - 请求的 cookie

  • response - 返回值来自处理程序

默认情况下,Elysia 会将传入的字符串化 JSON 消息解析为对象进行验证。

¥By default Elysia will parse incoming stringified JSON message as Object for validation.

配置

¥Configuration

你可以设置 Elysia 构造函数来设置 Web Socket 值。

¥You can set Elysia constructor to set the Web Socket value.

ts
import { Elysia } from 'elysia'

new Elysia({
    websocket: {
        idleTimeout: 30
    }
})

Elysia 的 WebSocket 实现扩展了 Bun 的 WebSocket 配置,更多信息请参阅 Bun 的 WebSocket 文档

¥Elysia's WebSocket implementation extends Bun's WebSocket configuration, please refer to Bun's WebSocket documentation for more information.

以下是 Bun WebSocket 的简要配置

¥The following are a brief configuration from Bun WebSocket

perMessageDeflate

@default false

为支持压缩的客户端启用压缩。

¥Enable compression for clients that support it.

默认情况下,压缩功能处于禁用状态。

¥By default, compression is disabled.

maxPayloadLength

消息的最大大小。

¥The maximum size of a message.

idleTimeout

@default 120

如果连接在指定秒数内未收到消息,则会关闭。

¥After a connection has not received a message for this many seconds, it will be closed.

backpressureLimit

@default 16777216 (16MB)

单个连接可缓冲的最大字节数。

¥The maximum number of bytes that can be buffered for a single connection.

closeOnBackpressureLimit

@default false

如果达到背压限制,请关闭连接。

¥Close the connection if the backpressure limit is reached.

方法

¥Methods

以下是 WebSocket 路由可用的新方法。

¥Below are the new methods that are available to the WebSocket route

ws

创建一个 websocket 处理程序

¥Create a websocket handler

示例:

¥Example:

typescript
import { Elysia } from 'elysia'

const app = new Elysia()
    .ws('/ws', {
        message(ws, message) {
            ws.send(message)
        }
    })
    .listen(3000)

类型:

¥Type:

typescript
.ws(endpoint: path, options: Partial<WebSocketHandler<Context>>): this
  • endpoint - 作为 websocket 处理程序公开的路径

  • options - 自定义 WebSocket 处理程序行为

WebSocketHandler

WebSocketHandler 从 config 扩展了配置。

¥WebSocketHandler extends config from config.

以下是 ws 接受的配置。

¥Below is a config which is accepted by ws.

open

用于连接新的 WebSocket 的回调函数。

¥Callback function for new websocket connection.

类型:

¥Type:

typescript
open(ws: ServerWebSocket<{
    // uid for each connection
    id: string
    data: Context
}>): this

message

用于接收 WebSocket 消息的回调函数。

¥Callback function for incoming websocket message.

类型:

¥Type:

typescript
message(
    ws: ServerWebSocket<{
        // uid for each connection
        id: string
        data: Context
    }>,
    message: Message
): this

Message 类型基于 schema.message。默认值为 string

¥Message type based on schema.message. Default is string.

close

用于关闭 websocket 连接的回调函数。

¥Callback function for closing websocket connection.

类型:

¥Type:

typescript
close(ws: ServerWebSocket<{
    // uid for each connection
    id: string
    data: Context
}>): this

drain

用于服务器已准备好接收更多数据的回调函数。

¥Callback function for the server is ready to accept more data.

类型:

¥Type:

typescript
drain(
    ws: ServerWebSocket<{
        // uid for each connection
        id: string
        data: Context
    }>,
    code: number,
    reason: string
): this

parse

Parse 中间件,用于在将 HTTP 连接升级到 WebSocket 之前解析请求。

¥Parse middleware to parse the request before upgrading the HTTP connection to WebSocket.

beforeHandle

Before Handle 中间件,用于在将 HTTP 连接升级到 WebSocket 之前执行。

¥Before Handle middleware which execute before upgrading the HTTP connection to WebSocket.

理想的验证位置。

¥Ideal place for validation.

transform

Transform 中间件,用于在验证之前执行。

¥Transform middleware which execute before validation.

transformMessage

类似 transform,但在验证 WebSocket 消息之前执行

¥Like transform, but execute before validation of WebSocket message

升级到 WebSocket 连接前需要添加的附加标头。

¥Additional headers to add before upgrade connection to WebSocket.