1、新建socket_service.js
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:1234')
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 => {
console.log('从服务端获取到了数据' + msg.data)
}
}
registerCallBack (callBack) {
console.log('回调函数的注册', callBack)
this.callBackMapping = callBack
}
unRegisterCallBack(callBack){
console.log('取消某一个回调函数', callBack)
this.callBackMapping = null
}
send (data) {
if (this.connected) {
this.sendRetryCount = 0
this.ws.send(data)
} else {
this.sendRetryCount++
setTimeout(() => {
this.send(data)
}, this.sendRetryCount * 500)
}
}
}
2、在main.js中全局引入实例并挂载到原型
import SocketService from '@/server/socket_service'
SocketService.Instance.connect()
Vue.prototype.$socket = SocketService.Instance
3、在vue组件中使用发送(客户端向服务端发送数据)
this.$socket.send(‘这是客户端发送的数据’)
4、在vue组件中使用接收(客户端接收服务端发送的数据)
1)注册回调函数
created(){
this.$socket.registerCallBack(this.testData)
}
2)取消回调函数
destroyed(){
this.$socket.unRegisterCallBack(this.testData)
}
3)接收到数据data
testData(data) {
console.log('获取到传感器websocket数据', data)
}