Websocket
兼容微信小程序和浏览器端
安装
npm install @rx-frontend/websocket
pnpm install @rx-frontend/websocket
yarn add @rx-frontend/websocket
使用
import createSocket from '@rx-frontend/websocket'
// createSocket(options, cbs, config)
const socket = createSocket(
{ url: 'ws://localhost:9876', },
{
onOpen: (res) => {
console.log('websocket is open now',res)
},
onMessage: (data) => {
console.log('onMessage')
},
onClose: (res) => {
console.log('websocket is close now', res)
}
onError: (res) =>{
console.log('websocket is error now', res)
}
}
)
options 参数
名称 | 类型 | 必填 | 说明 |
---|---|---|---|
url | string | 是 | 开发者服务器 wss 接口地址 |
protocols | Array. | 否 | 子组件协议 |
...args | any | 否 | 具体请参考 wx.connectSocket |
cbs参数
事件名 | 必填 | 说明 |
---|---|---|
onOpen | 否 | 监听 WebSocket 连接打开事件 |
onMessage | 否 | 监听 WebSocket 接受到服务器的消息事件 |
onClose | 否 | 监听 WebSocket 连接关闭事件 |
OnError | 否 | 监听 WebSocket 错误事件 |
config参数
名称 | 类型 | 默认值 | 说明 |
---|---|---|---|
timeout | number | 30 * 1000 | 心跳发送间隔(单位毫秒) |
retry | number | 5 * 1000 | 重连间隔时间(单位毫秒) |
maxRetryCount | number | 5 | 最大重连次数 |
immediate | boolean | true | 初始化时,是否立即建立连接 |
pingName | string | 'PING' | 客户端心跳发送内容 |
tongName | string | 'TONG' | 服务端心跳响应内容 |
返回事件
事件名 | 说明 | 参数 |
---|---|---|
connect | connect 连接事件 | |
send | websocket发送消息 | data:string |
close | websocket关闭事件, 默认code: 4000, 4000不触发重连事件 |