备注一个近期在做的我的项目下应用的 websocket 工具函数
(理论利用场景为,某院下的排队叫号零碎,须要应用到 websocket 连贯,且自定义回调函数并按需解决)
应用步骤大抵如下:
-
我的项目根门路下新建一个 websocket.js 文件,文件内容如下
let ws = null let _data = null let _url = null let _callback = null let hearBeatTimer = null let reconnectTimer = null let reconnectNum = 0 // 重连次数 const time = 3000 // 心跳距离 const reconnectTime = 5000 // 重连超时 export function webSocket(url = '', data ='', callback = () => {}) { // 初始化 _url = url // 地址 _data = data // 发送音讯 _callback = callback // 回调函数,利用闭包 createWebSocket() // 创立 webSocket} export function getWebSocket() {return ws} export function closeWebSocket() {console.log('敞开 WebSocket') if (ws) {ws.onerror = () => {} ws.onclose = () => {} ws.close()} ws = null _data = null _url = null _callback = () => {} // timeoutTimer = null hearBeatTimer = null reconnectTimer = null } function createWebSocket() {console.log('创立 WebSocket') if (!_url) return if (ws) {ws.close() ws = null } ws = new WebSocket(_url) ws.onopen = function() {sendMessage() heartBeat()} ws.onmessage = function(e) {console.log('音讯事件:', e) // clearTimeout(timeoutTimer) if (typeof _callback === 'function') {_callback(e) } reconnectNum = 0 heartBeat()} ws.onerror = function() {reconnect() } ws.onclose = function() {reconnect() } } function heartBeat() {if (hearBeatTimer) {clearTimeout(hearBeatTimer) } hearBeatTimer = setTimeout(() => {if (ws && ws.readyState === 1) { // 如果连贯失常 sendMessage() // setTimeoutTimer()} else {reconnect() } }, time) } function sendMessage() {console.log('发送音讯:', _data) if (!ws) return switch (Object.prototype.toString.call(_data)) {case '[object Object]': ws.send(JSON.stringify(_data)) break case '[object String]': ws.send(_data) } } function reconnect() {if (reconnectTimer) {clearTimeout(reconnectTimer) } reconnectTimer = setTimeout(() => { reconnectNum++ console.log('重连 WebSocket') console.log('重连次数:', reconnectNum) webSocket(_url, _data, _callback) }, reconnectTime) } window.onbeforeunload = () => {closeWebSocket() }
2. 在 app.vue 下援用并初始化 websocket
import {webSocket} from './websocket.js'
export default {created() {this.init()
},
methods: {init() {this.onWebSocket()
},
// 关上 socket
onWebSocket() {
// 模仿地址
const url = 'wss://www.baidu.com?uuid=‘// 心跳包发送内容
const data = {
to: -1,
text: 'ping', // 内容
}
console.log('data', data)
webSocket(url, data, this.handleWSCallBack)
},
// 解决 socket 回调
handleWSCallBack(data) {// console.log('data', e.data)
//do something
}
}
}
残余函数局部,各位小伙伴能够按需调整该回调参数
备注:以上 CODE 局部内容,要感激上面这位裘同学的帮忙,上面的他的某金账号,各位如有趣味能够关注下(外面干货略多)
某金账号