基本用法:
在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: