vue中使用socket连接后台

Posted pangchunlei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 在线测试(点击跳转

以上是关于vue中使用socket连接后台的主要内容,如果未能解决你的问题,请参考以下文章

从零开始的vue后台管理-连接数据库

iOS socket保持后台连接 ios9.0 xcode8.0

替换或删除后台堆栈上现有片段的代码不起作用

vue —— VSCode代码片段

vue —— VSCode代码片段

Socket 多人聊天室的实现(App后台接收消息的处理)