简介
前端websocket封装,ts编写,支持promise,支持心跳和重连机制
github 地址
使用
示例代码
安装
npm i pang-websocket
在vue中使用
<script>
import Vue from "vue";
import { WebsocketClass, eventBus } from "pang-websocket";
export default Vue.extend({
name: "Index",
mounted() {
const ws = new WebsocketClass(
"ws://localhost:3001/websocket/1",
{reConnectFn: this.handleReconnect}
);
eventBus.on("ws-open", this.handleWSOpen);
// 超过连接次数还未连接成功时触发该事件
eventBus.on("ws-close", this.handleWSClose);
ws.init();
// 如果不需要响应式 可以不放在data中
this.ws = ws;
},
methods: {
// 重连时的回调处理 需要返回promise resolve后 才会进行下一次重连
handleReconnect(times, e) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("reconnect", times, e);
resolve("done");
}, 2000);
});
},
handleWSOpen() {
this.ws.sendMsg("text", { name: "name" }).then((res) => {
console.log("handle res", res);
});
},
handleClick() {
this.ws.sendMsg("other", { other: "other" }).then((res) => {
console.log("handle other", res);
});
},
// 主动关闭链接
handleActiveClose() {
this.ws.closeWS().then((res) => {
console.log("close ws", res);
});
},
handleWSClose() {
console.log("reconnect fail close ws");
},
},
});
</script>
初始化WebsocketClass的参数
| 名称 | 类型 | 说明 |
|---|---|---|
| url | string | ws地址 |
| reLinkTimes | number | 重连次数 |
| heartbeatInterval | number | 前端重连的间隔,也是心跳的间隔 |
| heartbeatServerText | string | 后台心跳返回的值 |
| heartbeatClientText | string | 前端心跳发送的值 |
| reConnectFn | (times: number)=> Promise<any> | 在重连时,调用的回调函数,需要返回promise |
方法
/**
* @description 发送消息 返回promise 在后台返回对应的事件名称时resolve
* @param {string} event 与后台约定的事件名称
* @param {Record<string, any>} data 数据
* @return {Promise<any>}
*/
ws.sendMsg(event, data)
事件
-
ws-open 连接成功时触发的事件
-
ws-close 超过连接次数还未连接成功时触发该事件