websocket.js
import { store } from '../store'
/** 长链接,用于接收推送 */
class WsKeepAlive {
_isConnected =false
/**
*长链接,用于接收推送
*/
constructor (sendData) {
this.ws = new WebSocket('ws://192.168.17.69:8080/websocket/' + sendData.deviceCode) //建立连接时的传值
const that = this
this.ws.onopen = function open () {
console.log('WsKeepAlive opened')
that._isConnected = true
}
this.ws.onmessage = this.onMessage
this.ws.onerror = this.onError
this.ws.onclose = this.onClose.bind(this)
}
/**
* 是否连接成功
* @returns
*/
isConnected () {
return this._isConnected
}
/**
* webSocket数据接收通知
* @param {*} event
*/
onMessage (event) {
console.log('onMessage:' + event.data)
store.state.websocketData = event.data // 此处为websocket推送数据,存到vuex websocketData中
}
/**
* 断开webSocket链接
*
*/
closeWebsocket () {
this.ws.close()
}
/**
* 关闭事件通知
* @param {*} error
*/
onError (error) {
console.log('WsKeepAlive error:' + error)
}
/**
* 关闭事件通知
* @param {*} error
*/
onClose (error) {
console.log('WsKeepAlive closed:' + error)
}
/**
* 发送协议请求数据
* @param {*} msg
*/
//getPushData (msg) {
// const that = this
// return new Promise((resolve, reject) => {
// this.ws.send(msg)
// this.ws.onmessage = function name (event) {
// console.log('getPushData revData:' + event.data)
// resolve(event.data)
// that.ws.onmessage = that.onMessages
// }
// })
//}
}
export {WsKeepAlive}
使用:
<script>
import { WsKeepAlive } from '@/utils/websocket'
export default {
name: 'Monitor',
data () {
return {
getWS: null,
closeFlag: true,
pushData: []
}
},
computed: {
websocketData () {
return this.$store.state.websocketData //vuex websocket数据
}
},
watch: {
// 监听关闭值,断开websocket链接(需要断开时调用:this.getWS.closeWebsocket())
closeFlag (val) {
if (!val) {
this.getWS.closeWebsocket()
}
},
// 监听websocket推送数据
websocketData (val) {
if (val !== '连接成功!') { //第一次推送回的数据可能是'连接成功!'
this.pushData = JSON.parse(val) //处理推送数据
}
}
mounted(){
// 建立websocket连接
let sendData = {deviceCode: deviceCode}
this.getWS = new WsKeepAlive(sendData)
}
}
</script>