背景
一个简单的WebSocket聊天室的实现。
预览效果
以下展示数据为模拟数据。
具体实现
/** 连接 */
connectWebSocket() {
if ('WebSocket' in window) {
this.websocket = new WebSocket(process.env.VUE_APP_WS_BASE_API + '')
this.initWebSocket()
} else {
alert('当前浏览器不支持WebSocket,请更换为Chrome浏览器。')
}
},
/** webSocket初始化 */
initWebSocket() {
// 连接错误
this.websocket.onerror = this.setErrorMessage
// 连接成功
this.websocket.onopen = this.setOnopenMessage
// 收到消息的回调
this.websocket.onmessage = this.setOnmessageMessage
// 连接关闭的回调
this.websocket.onclose = this.setOncloseMessage
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = this.onbeforeunload
},
/** 连接错误事件通知处理 */
setErrorMessage() {
this.websocketStatus = 0
this.$notify.error({ title: '错误', message: '服务器连接失败,请刷新页面重试!' })
console.log(`log-WebSocket连接发生错误,状态码:${this.websocket.readyState}`)
},
/** 连接成功事件通知处理 */
setOnopenMessage() {
this.websocketStatus = 1
if (this.websocketReconnection !== 1) {
this.$notify({ title: '成功', message: '服务器连接成功', type: 'success' })
console.log(`log-WebSocket连接成功,状态码:${this.websocket.readyState}`)
}
if (this.websocketReconnection === 1) {
if (!this.roomOneId) {
return
}
if (!this.roomOneUserInfo.userId) {
return
}
console.log(`log-正在尝试重新加入【${this.roomOneTitle}】直播间...`)
// 业务方法 这里不展示
this.wsJoinRoom(this.roomOneId, this.roomOneUserInfo)
}
},
/** 收到消息事件通知处理 */
setOnmessageMessage(event) {
let data = JSON.parse(event.data)
// console.log(`log-服务端推送消息 data:${JSON.stringify(data)}`)
// 业务方法 这里不展示
// 大概就是:处理服务端推送消息 展示到前端
this.handleServerPushMsg(data)
},
/** 连接关闭事件通知处理 */
setOncloseMessage() {
this.websocketStatus = 0
this.websocketReconnection = 1
console.log(`log-WebSocket连接关闭,状态码:${this.websocket.readyState}`)
console.log(`log-正在尝试重新连接...`)
this.connectWebSocket()
},
/** 监听窗口关闭事件通知处理 */
onbeforeunload() {
this.closeWebSocket()
},
/** 关闭websocket */
closeWebSocket() {
this.websocket.close()
},
/** websocket发送消息 */
sendWebSocket(msg) {
this.websocket.send(msg)
},
这里只展示核心关于操作websocket的代码,具体相关业务实现代码不展示!
Q.E.D.