最近做了一个大屏项目,需要实时连接服务器,获取信息,和服务端商量以后决定使用websocket保持长连接,本人使用的技术栈是vue2,下面分享一下使用过程。
- 1.websocket一般使用是以ws开头的一个连接地址,在ws.js中导出该地址
export const wsRoute = 'ws://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
- 2.在vue文件引入该地址
import { wsRoute } from '@/utils/ws.js'
- 3.使用组件 reconnecting-websocket ,先npm安装再在vue文件引入
import ReconnectingWebsocket from 'reconnecting-websocket'
- 4.如果需要带一个参数在路径后面,一般可以拼接在路径后面,实际需要和后端对接,我这里是在wsRoute后面拼接了一个id;然后创建ws实例,监听ws的各个钩子方法;如果连接失败,需要重新连接 ,reconnect方法
initWebsocket() {
const user = this.user.login
const { id } = user || {}
// 拼接参数
const wsUrl = `${wsRoute}/${id}`
try {
// 创建ws实例,ws先事先定义一下
ws = new ReconnectingWebsocket(wsUrl)
// 调用 handleWebsocket 方法监听连接
this.handleWebsocket()
} catch (e) {
console.log(e, 'ws error try')
this.isReconnect = false
if (this.wsTimer) clearTimeout(this.wsTimer)
this.wsTimer = setTimeout(() => {
this.reconnect()
}, 10000)
}
},
handleWebsocket() {
ws.onerror = () => {
console.log('ws error onerror')
ws.close()
this.isReconnect = false
if (this.wsTimer) clearTimeout(this.wsTimer)
this.wsTimer = setTimeout(() => {
this.reconnect()
}, 10000)
}
ws.onopen = () => {
console.log('连接成功')
if (ws.readyState === 1) {
// ws.send('123') 可以根据需要发送参数给服务端,一般只能发送字符串
}
// setInterval(e => {
// if (ws.readyState === 1) {
// ws.send('123')
// }
// }, 30 * 1000)
}
// 处理数据
ws.onmessage = (e) => {
// 一般返回的数据在e.data中,而且是个字符串
const resData = JSON.parse(e.data)
console.log(resData, 'resdata')
if (resData.messageType === 'ON_BED_CHANGE') {
this.screen.onBedChange = Math.random()
}
if (resData.messageType === 'SLEEP_TAB_CHANGE') {
this.screen.timeSetChange = Math.random()
}
}
ws.onclose = () => {
console.log('websocket closed')
}
}
reconnect() {
if (this.isReconnect) return
this.isReconnect = true
this.initWebsocket()
}