1、初始化websocket
initWebSocket() {
const path = this.define.APIURl.replace('http', 'ws') + '/model'// 后台给的websocket的ip地址
this.websock = new ReconnectingWebSocket(path)
this.websock.onmessage = this.websocketOnMessage
this.websock.onopen = this.websocketOnOpen
this.websock.onerror = this.websocketOnError
this.websock.onclose = this.websocketClose
},
2、连接建立成功的信号
websocketOnOpen() {
console.log('初始化成功')// 连接成功后就可以在这里写一些回调函数
},
3、连接建立失败重连
websocketOnError() {
this.websock.close()
// 如果报错的话,在这里就可以重新初始化websocket,这就是断线重连
setTimeout(() => {
this.initWebSocket()
}, 1000)
},
4、数据接收
websocketOnMessage(e) {
// e这个变量就是后台传回的数据,在这个函数里面可以进行处理传回的值
var self = this;
let data = JSON.parse(e.data);
//对后台传回的数据进行操作
},
5、数据发送到后台
websocketSend(Data) {
this.websock.send(Data)// Data变量就是传给后台的数据
},
6、关闭
websocketClose() {
console.log('断开连接')
},