vue-cli3项目中使用websocket

基本用法:
在mounted的初始化websocket,在beforeDestroy中关闭连接
init() {
if (typeof WebSocket === 'undefined') {
alert('您的浏览器不支持socket')
} else {
// 实例化socket
this.socket = new WebSocket(
'wss://label-test.ainnovation.com/api/work_status/' // 此处使用wss是后端配置过,保证在https下不被拦截
)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
}
},
open() {
console.log('socket连接成功')
this.send()
},
error() {
console.log('连接错误')
},
getMessage(msg) {
console.log(msg)
// 此处看后端返回,后端可能会1s返回一次消息,按需实现
// 比如做提交和审批的需求就需要实现如下逻辑:
// A提交 => B出现审批提示 (出现一次,存id,不出现保证不重复弹出)=> B关闭/审批(请求接口,标记为已查看,去掉id,才能保证A再次提交这个id,B还能看到)
},
send() {
// websocket请求无法设置请求头,在此采用建立连接之后主动推送token和userId给后端
const token = this.$cookies.get('auth')
const userId = this.$cookies.get('user_id')
this.socket.send(
JSON.stringify({
auth: token,
user_id: userId,
params: {
headers: {
Connection: 'upgrade' // 此处看后端要求
}
}
})
)
},
close() {
console.log('socket已经关闭')
}
在https下使用webscoket可能会报如下错误:
需要后端进行相应配置,对应如上wss:

posted @ 2020-09-01 16:59  风吹叶不飘  阅读(4507)  评论(0编辑  收藏  举报