declare const window: any export default class Ws { private websocket: WebSocket private onerror: (e: any) => void private onclose: (e: any) => void constructor({ url, params, operate, onClose }) { let wsUrl = window.VUE_WSAPI || `wss://websocket.sieiot.com/ws` if (window.WebSocket) { this.websocket = new WebSocket(wsUrl) // 建立连接 this.websocket.onopen = this.onopen(params) // 接收消息 this.websocket.onmessage = this.onmessage(operate) // 连接出错 this.websocket.onerror = this.onerror // 关闭连接 this.websocket.onclose = onClose || this.onclose window.onclose = this.close } } onopen(params) { return async (event) => { // 绑定 websocket 服务 this.websocket.send(JSON.stringify({ ...params })) return event } } onmessage(operate) { return (event) => { operate(event) } } close() { if (this.websocket.readyState !== this.websocket.CLOSED) this.websocket.close() } // 防止 websocket 掉线,发送 params 为字符串 'heartbeat' send(params) { this.websocket.send(params) } }