zoukankan      html  css  js  c++  java
  • 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 在线测试(点击跳转

  • 相关阅读:
    ueditor单独调用图片上传
    百度Ueditor多图片上传控件
    linux基础之vim编辑器
    linux基础之进阶命令二
    linux基础之基础命令一
    Python基础之PyCharm快捷键大全
    IT菜鸟之VTP应用项目
    IT菜鸟之总结(Du teacher)
    IT菜鸟之DHCP
    IT菜鸟之路由器基础配置(静态、动态、默认路由)
  • 原文地址:https://www.cnblogs.com/pangchunlei/p/12539132.html
Copyright © 2011-2022 走看看