vue中使用socket连接后台

1、需求背景

  工程车巡检,实时发送巡检位置信息、现场状况到服务器,页面实时显示工程车位置以及状况信息

2、VUE中使用socket建立实时连接

3、mounted生命周期中初始化连接

 

mounted () {this.initWebSocket()
},

 

4、socket连接方法

 

/**
     * 建立socket连接,调用时间:
     * 1.首次进入页面,如果不是查看记录,请求出来初始数据后,建立socket连接
     * 2.调用数据库查询完毕后
     * */
    initWebSocket() { //初始化weosocket 
      const wsuri = 'ws://121.40.165.18:8800/'
      this.websock = new WebSocket(wsuri)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() { //连接建立之后执行send方法发送数据
      let actions = {'tags': ['ypt/leak/textplantrecord/getlist'],'machineid':'18279'}
      this.websocketsend(JSON.stringify(actions))
    },
    /**
     * 连接建立失败,断开连接
     * 1.查询一次数据库数据
     * 2.查询完后再次建立socket连接
     * */
    websocketonerror() {//连接建立失败重连
      let _this = this
      console.log('连接建立失败')
      //this.websock.onclose()
      this.initWebSocket()
    },
    websocketonmessage(e) { //数据接收
      //const redata = JSON.parse(e.data)
      console.log(e.data)
      this.dealF2DataList(redata)
    },
    websocketsend(Data) {//数据发送
      this.websock.send(Data)
    },
    websocketclose(e) {  //关闭
      console.log('断开连接', e)
    },

 

5、连接状态

 

6、数据输出(在websocketonmessage里调用数据处理方法)

 

7、WebSocket 在线测试(点击跳转

posted @ 2020-03-21 14:09  庞某人  阅读(7726)  评论(0编辑  收藏  举报