@likg/websocket
Version:
Websocket APIs
3 lines (2 loc) • 2.17 kB
JavaScript
/* eslint-disable */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).kWebsocket=t()}(this,(function(){"use strict";return class{options;socket=null;normalCloseFlag=!1;reconnectTimes=1;reconnectTimer=null;heartbeatTimer=null;constructor(e){this.options=Object.assign({},{debug:!1,maxReconnectTimes:5,reconnectInterval:1e4,heartInterval:1e4,heartString:"heartbeat"},e),this.init()}init(){this.socket=new WebSocket(this.options.url),this.watch()}watch(){this.socket&&(this.socket.onopen=()=>{this.options.debug&&console.log("WebSocket:链接打开"),this.options.onConnected(),this.reconnectTimes=1,this.sendHeartbeat()},this.socket.onmessage=e=>{e.data!==this.options.heartString&&(this.options.debug&&console.log("WebSocket:接收到消息 → ",e.data),this.options.onMessage(e.data))},this.socket.onclose=()=>{this.normalCloseFlag?this.options.debug&&console.log("WebSocket:正常关闭"):(this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.reconnect())})}close(){this.normalCloseFlag=!0,this.socket?.close(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}send(e){this.socket?.send(JSON.stringify(e)),this.options.debug&&console.log("WebSocket:消息已发送")}sendHeartbeat(){this.socket?.send(this.options.heartString),this.options.debug&&console.log("WebSocket:💓"),this.heartbeatTimer=setInterval((()=>{this.socket?.send(this.options.heartString),this.options.debug&&this.options.debug&&console.log("WebSocket:💓")}),this.options.heartInterval)}reconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectTimes<=this.options.maxReconnectTimes?this.reconnectTimer=setTimeout((()=>{this.options.debug&&console.log(`Websocket:第${this.reconnectTimes}次重连...`),this.init(),this.reconnectTimes++}),this.options.reconnectInterval):this.options.debug&&console.log("WebSocket:重连失败")}}}));