【土旦】Vue+WebSocket 实现长连接

时间:2023-03-09 13:20:40
【土旦】Vue+WebSocket 实现长连接

1.websocket 连接代码


created() {
this.initWebsocket()
},
methods: {
// 初始化websocket
initWebsocket() {
let _this = this
let ws = new WebSocket(this.wsUrl)
//保持连接
ws.onopen = () = > {
// Web Socket 已连接上,使用 send() 方法发送数据
//console.log('数据发送中...')
setInterval(() = > {
let msg = {
msg: '心跳内容'
}
ws.send(JSON.stringify(msg))
}, 5000)
//console.log('数据发送完成')
}
//数据接收
ws.onmessage = evt = > {
_this.websocketonmessage(evt)
//console.log('数据已接收...')
}
// 关闭 websocket 时的 钩子
ws.onclose = () = > {
//console.log('连接已关闭...')
_this.websocket()
}
// 路由跳转时结束websocket链接
this.$router.afterEach(() = > {
ws.close()
})
},//数据接收
websocketonmessage(e) {
// 数据处理
let obj = JSON.parse(e.data)
}
}