实际工作中可能会遇到需要封装WebSocket的场景,以下基于vue做了WebSocket的封装,包括心跳机制和重连
// 创建构造函数
const QueryWebSocket = function (obj) {
obj = obj || {}
obj.url = `wss://${process.env.NODE_ENV === "development" ? "xxx.xxx.com" : location.host}${obj.url}`
const defaultObj = {
url: '',
lockReconnect: false,
ws: '',
tt: '',
timeout: 30000,
timeoutObj: null,
queryData(){}
}
this.config = Object.assign(defaultObj, obj)
if ('WebSocket' in window) {
// console.log('支持WebSocket')
const that = this
setTimeout(function () {
that.createWebSocket()
}, 1000)
} else {
alert('该浏览器不支持WebSocket')
}
}
QueryWebSocket.prototype = {
QueryWebSocket: QueryWebSocket,
reset: function () {
const that = this
clearInterval(that.config.timeoutObj)
// console.log('进入此处关闭连接的吗')
this.config.ws.onclose()
},
start: function () {
const that = this
that.config.timeoutObj = setInterval(function () {
const message = 'I'
that.config.ws.send(message) // 启动心跳
}, 15000)
},
// 创建webSocket
createWebSocket: function () {
try {
// 成功
// console.log('createWebSocket');
this.config.ws = new WebSocket(this.config.url)
this.webSocketInit() // 初始化webSocket连接函数
// this.config.createSuccess()
} catch (e) {
// 失败
// console.log(e,'catch')
// 重连函数
this.webSocketReconnect(this.config.url)
}
},
// 像websocket发送信息
sendContent: function (data) {
this.config.ws.send(JSON.stringify(data))
},
// 初始化方法,成功后执行
webSocketInit: function () {
const that = this
// 连接关闭函数
that.config.ws.onclose = function (type) {
// // console.log('type会传进来么', type)
// // console.log('连接已关闭...', new Date())
clearInterval(that.config.timeoutObj)
if (type !== 'close') {
setTimeout(() => {
that.webSocketReconnect(that.config.url) // 如果连接关闭则重连
}, 3000)
} else {
that.config.ws.close()
that.config.ws = null
that.lockReconnect = true
}
}
// 连接错误函数
that.config.ws.onerror = function () {
// console.log('连接错误...', new Date())
clearInterval(that.config.timeoutObj)
setTimeout(() => {
that.webSocketReconnect(that.config.url) // 如果连接错误则重连
}, 3000)
}
// 连接建立,发送信息
that.config.ws.onopen = function () {
// // console.log('链接成功')
that.config.ws.send('I')
that.start() // 订阅业务发送之后启动心跳检测机制
}
// 业务订阅成功后接受服务端推送消息 ,其实是个字符串
that.config.ws.onmessage = function (evt) {
if (evt.data !== 'O') {
if (JSON.parse(evt.data).content !== 'PONG') {
that.config.queryData(JSON.parse(evt.data))
}
}
}
},
// 重连
webSocketReconnect: function (url) {
// console.log('reconnect');
const that = this
if (that.lockReconnect) {
return
}
// // console.log('socket 连接断开,正在尝试重新建立连接')
that.lockReconnect = true
that.tt && clearTimeout(that.tt)
that.tt = setTimeout(function () {
that.lockReconnect = false
that.createWebSocket(url)
}, 4000)
}
}
export default QueryWebSocket
使用示例
项目中导入QueryWebSocket
import QueryWebSocket from './websocket'
methods中写入方法
createWebSocket() {
let url = `这里写wss地址`
this.webSocket = new QueryWebSocket({
url: url,
queryData: () => {
},
})
},