tcsl-websocket-framework
v0.0.9
Published
一个基于typescript封装websocket的业务SDK,重点是简单性、可靠性和可扩展性。主要目的是保证web客户端和服务端的连接,具有心跳检测和自动重连机制。当客户端设备出现网络中断或服务器错误导致websocket断开连接时,程序将自动重新连接,直到重新连接成功。
Downloads
14
Readme
tcsl-websocket-framework
一个基于typescript封装websocket的业务SDK,重点是简单性、可靠性和可扩展性。主要目的是保证web客户端和服务端的连接,具有心跳检测和自动重连机制。当客户端设备出现网络中断或服务器错误导致websocket断开连接时,程序将自动重新连接,直到重新连接成功。
为什么
当我们使用原生websocket 时,如果网络断开,则不会执行任何事件函数。所以前端程序不知道websocket断开了。但是如果程序现在正在执行WebSocket.send(),浏览器必须发现消息信号失败,所以 onclose 函数会执行。
后端websocket服务很可能会发生错误,当websocket断开连接时,前端没有收到通知消息。所以需要通过超时发送ping消息。当服务器收到 ping 消息时,服务器向客户端返回 pong 消息。因为收到 pong 消息,客户端知道连接正常。如果客户端没有收到 pong 消息,则是连接异常,客户端将重新连接。
综上所述,为了解决以上两个问题。客户端应主动发送 ping 消息以检查连接状态。
特征
- 无依赖、体积小
- 使用浏览器原生的websocket功能
- 当连接丢失时会重新连接
- 高测试覆盖率和代码内文档,使您能够轻松修改和扩展代码
安装
在您项目的根目录中
npm install tcsl-websocket-framework
在您的项目代码中
import { Socket } from 'tcsl-websocket-framework'
默认配置
// 重连上限默认值
RECONNECT_LIMIT: 5,
// 重连间隔基值(2秒)
RECONNECT_INTERVAL: 2000,
// 心跳间隔
HEART_INTERVAL: 5000,
// 心跳超时时间
HEART_OVERTIME: 10000,
// 服务端发送的关闭状态码,只有 1000 是正常关闭,其他全是错误状态
CLOSE_NORMAL: 1000,
PING: {
wsCode: "framework_ping",
},
PONG: {
wsCode: "framework_pong",
},
用法
初始化
使用提供的创建一个新实例Socket:
const ws = new Socket({url: 'wss://xxxxxxxx'})
回调
- socket连接成功的回调函数
ws.openCallback = (res) => {
console.log(res)
}
- socket关闭的回调函数
ws.closeCallback = (res) => {
console.log(res)
}
- socket异常的回调函数
ws.errorCallback = (res) => {
console.log(res)
}
方法
- socket一次订阅主题
ws.subscribeOnce('login',(data:any)=>{
console.log('login订阅返回的数据: ', data);
})
- socket订阅主题
ws.subscribe('login',(data:any)=>{
console.log('login订阅返回的数据: ', data);
})
- 取消订阅
ws.unsubscribe('login',(data:any)=>{
console.log('login订阅返回的数据: ', data);
})
- 发送消息
ws.sendMsg({
wsCode: 'login',
data: {name: 'aaa', password:'2222'}
})
- 手动关闭
ws.close()