利用html5 的websocket去连接服务端的websocket,实现前端与服务端双向通信
1. 示例代码
为了使得全局可以控制WebSocket,将实例挂载到vue原型链上
import Vue from 'vue'
Vue.prototype.$ws = undefined // 只在这里做了一个定义,如果直接创建实例,会立刻建立连接
// 初始化Websocket
initWebsocket() {
let that = this
this.$ws = new WebSocket('ws://192.168.2.122:7003/api/hnt/websocket/link?id=123')
this.$ws.onopen = function (evt) {
that.onOpen(evt)
}
this.$ws.onclose = function (evt) {
that.onClose(evt)
}
this.$ws.onmessage = function (evt) {
that.onMessage(evt)
}
this.$ws.onerror = function (evt) {
that.onError(evt)
}
},
onMessage(e) {
console.log('接收到消息!', e)
},
onClose(e) {
console.log('断开连接!', e)
},
onOpen(e) {
console.log('建立连接!', e)
},
onError(e) {
console.log('出错啦!', e)
},
send() {
this.$ws.send('这是一条消息!') // 向服务端发送数据
},
closeSocket() { // 手动断开连接
this.$ws.close()
},