websocket--信息推送和接收

时间:2025-01-30 07:42:49
// mixins/ export default { data () { return { message: 'hello', // websocket相关配置 wsUrl: '', // 此处格式为地址加端口号,例: 'ws://119.*.*.*:8888' websocket: null, // 建立的连接 lockReconnect: false, // 是否真正建立连接 timeout: 30 * 1000, // 3o秒一次心跳 timeoutObj: null, // 心跳倒计时 //serverTimeoutObj: null, // 心跳倒计时-计时器-当时为了心跳超时直接关闭,不重连做的预留 timeoutnum: null, // 断开 重连倒计时 connectState: 0 // 连接状态 } }, mounted () { let that = this setTimeout(() => { that.initWebSocket() }, 300) }, // 页面销毁,关闭websocket destroyed () { if (this.websocket && this.websocket.readyState === 1) { this.websocket.close() } }, methods: { // websocket通讯初始化 initWebSocket () { let urli = this.wsUrl this.websocket = new WebSocket(urli) this.websocket.onopen = this.onopen this.websocket.onmessage = this.onmessage this.websocket.onclose = this.onclose this.websocket.onerror = this.onerror }, // 重新链接ws reconnect () { // 重新连接 var that = this if (that.lockReconnect) { return } that.lockReconnect = true // 没连接上会一直重连,设置延迟避免请求过多 that.timeoutnum && clearTimeout(that.timeoutnum) that.timeoutnum = setTimeout(function () { // 新连接 that.initWebSocket() that.lockReconnect = false }, 5000) }, reset () { // 重置心跳 var that = this // 清除时间 clearTimeout(that.timeoutObj) clearTimeout(that.serverTimeoutObj) // 重启心跳 that.start() }, // 心跳检测 start () { // 开启心跳 var self = this self.timeoutObj && clearTimeout(self.timeoutObj) // && clearTimeout() self.timeoutObj = setTimeout(function () { // 这里发送一个心跳,后端收到后,返回一个心跳消息, if (self.websocket.readyState === 1) { // 如果连接正常 self.websocket.send('heartCheck') self.reset() } else { // 否则重连 self.reconnect() } // 以下代码多余 // = setTimeout(function () { // 超时关闭 // () // }, ) }, self.timeout) }, // 开启ws onopen () { // 获取连接状态值 this.connectState = this.websocket.readyState // 开启心跳 this.start() }, // ws发送数据 sendData (data, type) { this.websocket.send('你好,服务器', data) }, // ws获取数据 onmessage (e) { console.log('服务器返回的数据', e.data) // 收到服务器信息,心跳重置 this.reset() }, // ws关闭 onclose (e) { console.log('连接关闭') if (this.websocket.readyState === 1) { this.websocket.close('close') } // 重连 this.reconnect() }, // ws错误后重新连接 onerror (e) { console.log('出现错误') // 重连 this.reconnect() } } }