# h5-ws **Repository Path**: towardly/h5-ws ## Basic Information - **Project Name**: h5-ws - **Description**: h5 websocket - **Primary Language**: Unknown - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-03-18 - **Last Updated**: 2024-09-04 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # h5-ws H5 Websocket ## 特性 1. 同时支持 `node` 和 `h5` 2. 自动重连 3. 离线消息缓存 ## 安装 ```bash npm install @asteres/websocket --save ``` ## 使用 ```js import Ws from "@asteres/websocket"; const options = { /** 是否开启断线重连, 默认: true */ reconnection: true, /** 最大重连次数, -1 则一直重连, 默认: 5 */ maxRetries: 5, /** 断线时,缓存的发送的消息列表大小, -1 - 无限大小, 默认: 0 */ maxCacheSize: 0, /** {@link https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket/WebSocket#protocols 协议数组} */ protocols?: string | string[]; /** 自定义日志记录器, 默认为: console */ logger?: { info: (msg: string) => void; warn?: (msg: string) => void; error?: (msg: string) => void; }, /** * WebSocket 客户端, 如果不想用原生, 可以指定库, 例如: 在 node 环境可以替换为 ws * * 示例: * import WebSocket from 'ws' * import Ws from '@asteres/websocket' * * const ws = new Ws("", { * target: WebSocket * }); */ target?: globalThis.Websocket; }; const ws = new Ws("ws://localhost:8080", options); // 服务端使用 Pino 日志 import Pino from 'pino' const logger = Pino() const ws = new Ws("ws://localhost:8080", { logger }) ``` `options` 参数为选填 ## 方法 ### 1. `constructor(url: string, options?: WsOption)` ### 2. `on(type: 'open' | 'close' | 'error' | 'message', handler: WsEvent)` ### 3. `off(type: 'open' | 'close' | 'error' | 'message', handler: WsEvent)` > 注意: 为了 `off` 能正常工作,务必 `on` 的函数不要直接写回调函数 ### 4. `send(data: string | object | ArrayBuffer | Blob | ArrayBufferView, isCache?: boolean): boolean` 发送消息, 跟原生方法相比, 支持普通的 `JSON` 对象,如果是普通的 `JSON` 对象,会自动转换为 `JSON` 字符串; 如果断线会返回发送失败 参数说明: - `data`: 消息体 - `isCache`: 如果断线时,是否缓存消息, 默认: `true` > 注意: 消息是否缓存,除了跟 `isCache` 参数有关,还跟配置连接时 `maxCacheSize` 配置项有关,如果这个配置项设置为 `0` 也不会缓存;这个配置项默认为 `0` ### 5. `close(code?: number, reason?: string, destroy?: boolean)` 断开连接 参数说明: - `code`: 关闭连接的状态码, 默认: `1000` - `reason`: 关闭连接的原因, 默认: `""` - `destroy`: 是否销毁连接, 默认: `true`;如果为 `true` 则销毁后无法通过 `connect` 重连 ### 6. `connect()` 连接到 WebSocket 服务器 > 注意: 如果创建连接时, `reconnection` 配置项为 `false`, 则需要手动调用该函数进行连接