zoukankan      html  css  js  c++  java
  • vue使用websocket

    initWebSocket() {
        //初始化websocket
       this.ws = new WebSocket(url) // 在data中定义ws为null
        this.ws.onmessage = this.websocketonmessage
        this.ws.onopen = this.websocketonopen
        this.ws.onerror = this.websocketonerror
         this.ws.onclose = this.websocketclose
        },
        websocketonopen() {
         // 连接websocket成功时的回调
        console.log('连接成功')
       },
      websocketonmessage(e) {
        //获取websocket推送的数据
        let re_msg = e.data
        // 转码,防止有百分号出现
        re_msg = unescape(re_msg.replace(/\u/g, '%u'))
        re_msg = JSON.parse(re_msg)
       },
       // 连接失败时重新连接
       websocketonerror() {
        this.initWebSocket()
       },
       // 断开链接后报错
       websocketclose(e) {
        this.initWebSocket()
       },注意:如果需要发送心跳的话,只需要在onopen里写一个定时器,定时发送心跳数据即可,离开页面时记得清除定时器。例:
    
    setInterval(() => {
        if (_this.ws != null && _this.ws.readyState == _this.ws.OPEN) {
         let req = {
          自定义字段: '自定义数据',
         }
         _this.ws.send(JSON.stringify(req))
        }
       }, 7500)
  • 相关阅读:
    Java学习之路
    ofo开锁共享平台
    Texstudio
    我的母亲 (老舍)
    Excel数据透视表
    Excel分类汇总与数据有效性
    Tomcat源码分析
    证明:在任意六人的聚会中,要么有三人曾经认识,要么有三人不曾认识
    琅琊榜读书笔记
    选择排序可视化
  • 原文地址:https://www.cnblogs.com/lyt520/p/14573411.html
Copyright © 2011-2022 走看看