WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
为了方便使用webSocket,自定义js方法
js方法,可用
const WSSURI = webSocket请求地址
export default {
data() {
return {
destroy: false, // 彻底断开连接
websock: null, // ws 对象
lockReconnect: false, // ws重连标记
wsRecontt: undefined, // ws重连超时时间
timeout: 3000, // ws心跳超时时间
timeoutObj: null, // ws心跳超时对象
serverTimeoutObj: null // ws服务超时对象
}
},
created() {
this.userName = sessionStorage.getItem('*******') // 获取数据参数
// 初始化连接
this.initWebSocket()
},
methods: {
// 初始化websocket连接
initWebSocket() {
const wsuri = WSSURI + "?userName=" + this.userName; // websocket请求地址+参数
try {
// console.log('>>>Ws init connect ....... ')
this.websock = new WebSocket(wsuri)
this.initWs()
} catch (e) {
console.error('Init Ws Connect Error.', e)
this.reconnect()
}
},
// 重新连接
reconnect() {
const self = this
if (this.lockReconnect) {
return
}
this.lockReconnect = true
// 没连接上会一直重连,设置延迟避免请求过多
if (this.wsRecontt) {
clearTimeout(this.wsRecontt)
}
this.wsRecontt = setTimeout(function() {
self.initWebSocket()
self.lockReconnect = false
}, 3000)
},
// 初始化连接函数
initWs() {
const self = this
this.websock.onmessage = this.websocketonmessage
this.websock.onopen = function() {
// 心跳检测重置
self.heartCheck()
console.log('WSS连接已建立:'+new Date().toLocaleString())
}
this.websock.onerror = function(e) {
console.warn('WSS连接发生错误......', e)
if (!self.destroy) {
self.reconnect()
}
}
this.websock.onclose = function(e) {
console.warn('WSS断开连接,code:' + e.code + ',' + +new Date().toLocaleString())
if (!self.destroy) {
self.reconnect()
}
}
},
// 心跳检测
heartCheck() {
const self = this
if (this.timeoutObj) {
clearTimeout(this.timeoutObj)
}
if (this.serverTimeoutObj) {
clearTimeout(this.serverTimeoutObj)
}
this.timeoutObj = setTimeout(function() {
// 这里发送一个心跳,后端收到后,返回一个心跳消息
self.websock.send('0')
// console.info('>>> Heart check ......')
self.serverTimeoutObj = setTimeout(function() {
// console.info('>>> Server timeout check ... Websocket close. Try reconnecting ... ')
self.websock.close()
}, self.timeout)
}, self.timeout)
},
// 数据接收
websocketonmessage(e) {
// console.log(e, 'websocket接收到的数据')
this.heartCheck()
if (e && e.data) {
if (e.data == '1') {
// 心跳, do nothing ...
} else {
// 业务数据处理
try {
const resdata = JSON.parse(e.data)
this.wsonmessageHandle(resdata)
} catch (e) {
console.error(
'>>> Server Response data is not valid json string.',
e
)
}
}
}
},
// 数据业务处理
wsonmessageHandle(resdata) {
// console.log(resdata);
}
}
}
页面中使用
在utils包下新建wss.js文件并引入到所需要的页面中
import wss from '@/utils/wss'
export default {
components: {},
mixins: [wss],
}
// 云端推送数据处理
wsonmessageHandle(resdata) {
console.log('WS Received:', resdata)
...
}
注意:在单独某些页面使用的时候切记要在beforeDestroy里进行销毁,虽然是轻量级,但不用的时候是还是断开吧。
beforeDestroy() {
}
初学者,有不足或不完善之处望各位朋友指正。感谢