WebSocket的应用和实现
1. 什么是WebSocket
WebSocket 是 HTML5 中的协议,支持持久连接,http协议不支持持久性连接。
2. WebSocket 是什么样的协议,具有什么优点
HTTP 的声明周期通过Request来界定,也就是一个Request一个Response,而且Response是被动的,不能主动发起。
WebSocket 是基于HTTP协议的,借用了Http协议来完成一部分握手,在握手阶段与HTTP是相同的。
3. vue中WebSocket
initWebSocket () {
// 获取WebSocket连接信息
this.$api('systemManage', {}).then(res => {
if (res.code != 0) return
let socketWs = res.data.socketWs
let socketWss = res.data.socketWss
let wsuri = ''
let ishttps = document.location.protocol == 'https:'
if (ishttps) {
wsuri = 'wss:' + socketWss// wss地址
} else {
wsuri = 'ws:' + socketWs// ws地址
}
// console.log(wsuri)
this.websock = new WebSocket(wsuri)
this.websock.onopen = this.websocketonopen
this.websock.onerror = this.websocketonerror
this.websock.onmessage = this.websocketonmessage
this.websock.onclose = this.websocketclose
}).catch(err => {
this.$Message.error(err.message)
})
},
websocketonopen () {
// console.log('WebSocket连接成功' + '状态码' + this.websock.readyState)
this.websocketsend('userJoin&chronic&' + this.userInfo.token)
},
websocketonerror (e) { // 错误
// console.log('WebSocket连接发生错误')
},
websocketonmessage (e) { // 数据接收
// console.log('接收数据:' + e.data)
this.websockTimeMersure++
},
websocketsend (agentData) { // 数据发送
// console.log('数据发送' + agentData)
this.websock.send(agentData)
},
websocketclose () { // 关闭
// console.log('websocket关闭')
// this.websocketsend('userLeave&chronic&' + this.userInfo.token)
},