- 封装websocket
export default class SocketService {
static instance = null
static get Instance () {
if (!this.instance) {
this.instance = new SocketService()
}
return this.instance
}
ws = null
callBackMapping = {}
connected = false
sendRetryCount = 0
connectRetryCount = 0
connect () {
if (!window.WebSocket) {
return console.log('您的浏览器不支持WebSocket')
}
this.ws = new WebSocket('ws://localhost:8000')
this.ws.onopen = () => {
console.log('连接服务端成功了')
this.connected = true
this.connectRetryCount = 0
}
this.ws.onclose = () => {
console.log('连接服务端失败')
this.connected = false
this.connectRetryCount++
setTimeout(() => {
this.connect()
}, 500 * this.connectRetryCount)
}
this.ws.onmessage = msg => {
const recvData = JSON.parse(msg.data)
const type= recvData.type
if (this.callBackMapping[type]) {
const realData = JSON.parse(recvData.data)
this.callBackMapping[type].call(this, realData)
}
}
}
registerCallBack (type, callBack) {
this.callBackMapping[type] = callBack
}
unRegisterCallBack (type) {
this.callBackMapping[type] = null
}
send (data) {
if (this.connected) {
this.sendRetryCount = 0
this.ws.send(JSON.stringify(data))
} else {
this.sendRetryCount++
setTimeout(() => {
this.send(data)
}, this.sendRetryCount * 500)
}
}
}
- 在main.js中引入
import SocketService from '@/utils/socket_service'
SocketService.Instance.connect()
Vue.prototype.$socket = SocketService.Instance
- 在组件中的使用
created() {
this.$socket.registerCallBack('data', this.getData)
},
mounted() {
this.$socket.send({
type: 'data',
})
},
destroyed() {
this.$socket.unRegisterCallBack('data')
},
methods: {
getData(ret) {
this.allData = ret
},
}
|