搞一下常用的websocket的使用和心跳

websocket 和HTTP请求的不同点:

bash 复制代码
1.WebSocket是双向通信协议,HTTP是单向的
WebSocket是双向通信协议,模拟Socket协议,可以双向发送或接受信息。而HTTP是单向的

2.连接方式不同
WebSocket是需要浏览器和服务器握手进行建立连接的。
http是浏览器发起向服务器的连接,服务器预先并不知道这个连接。

3.协议开头不同
websocket:websocket的协议是以 ws/wss 开头。
http 对应的是 http/https

4.连接长度不同
websocket是持久连接。http 是短连接。

废话不多说,直接上代码 公共文件websocket.js

kotlin 复制代码
import bus from "../utils/bus"
export default {
  data() {
    return {
      socket: null,
      heartbeatTimer: null,
    }
  },
  methods: {
    //websocket----开始
    initWebSocket(e, type) {
      this.socket = null;
      let devIP = '';
      if (process.env.VUE_APP_HOST_SERVER) {
        const match = process.env.VUE_APP_HOST_SERVER.match(/\/\/([^/]+)/);
        if (match && match[1]) {
          devIP = match[1];
        }
      }
      let wsUri = `ws://${devIP}/dispatch/ws`;
      if (process.env.NODE_ENV !== "development") {
        if (window.location.protocol === 'https:') {
          wsUri = `wss://${location.host}/dispatch/ws`
        } else {
          wsUri = `ws://${location.host}/dispatch/ws`
        }
      }
      if ("WebSocket" in window) {
        this.socket = new WebSocket(wsUri, ['protocol1'], {
          headers: {
            'x-token': this.token// 设置认证Header
          }
        }); //这里面的this都指向vue
      }
      this.socket.onopen = this.connectionOpen;
      this.socket.onerror = this.webSocketOnError;
      this.socket.onmessage = this.webSocketOnMessage;
      this.socket.onclose = this.closeWebsocket;
      // this.socket.onSend = this.webSocketSend;
      return this.socket;
    },

    connectionOpen(e) {
      // 链接建立的时候触发
      console.log("Websocket 连接成功")
      this.webSocketsend()
    },
    webSocketOnError(e) {
      console.log("WebSocket连接发生错误")
    },
    webSocketOnMessage(e) {
      const data = JSON.parse(e.data);
      // console.log('接收消息',data);

    },
    // 关闭websiocket
    closeWebsocket() {
      console.log("连接已关闭...");
      this.socket.close(); // 关闭 websocket
      this.stopHeartbeat()
      this.socket.onclose = function (e) {
        console.log("关闭");
      };
    },
    close() {
      this.socket.close(); // 关闭 websocket
      this.stopHeartbeat()
      this.socket.onclose = function (e) {
        console.log("关闭");
      };
    },
    webSocketsend() {
      console.log("发送...", this.socket)
      this.socket.send(JSON.stringify(this.agentData));
      this.startHeartbeat()
    },
    // 启动心跳
    startHeartbeat() {
      this.stopHeartbeat()
      const HEARTBEAT_INTERVAL = 30 * 1000
      const MAX_SILENCE = 120 * 1000
      let lastActivity = Date.now()
      const checkHeartbeat = () => {
        if (Date.now() - lastActivity > MAX_SILENCE) {
          console.warn('心跳超时,尝试重连',this.socket.readyState === WebSocket.OPEN)
          this.close();
          const payload = JSON.stringify({ business_type: 'heartBeat' })
          this.socket.send(payload)
          return
        }
        if (this.socket.readyState === WebSocket.OPEN) {
          const payload = JSON.stringify({ business_type: 'heartBeat' })
          this.socket.send(payload)
          lastActivity = Date.now()
          console.log('发送心跳:', payload)
        }
      }
      this.heartbeatTimer = setInterval(checkHeartbeat, HEARTBEAT_INTERVAL)
    },
     // 停止心跳
    stopHeartbeat() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer)
        this.heartbeatTimer = null
      }
    },
    //websocket----结束
  }
}

当然也可以搞成全局的

javascript 复制代码
//main.js
import websocket from "@/plugins/websocket"; //引入公共js
Vue.prototype.$websocket = websocket;//全局使用

其他文件使用xxx.vue

kotlin 复制代码
import myMixin from "../../../command/src/mixins/websocket";

//防止一直发送请求
infoFn() {
      bus.$off("baseDeviceList");
      bus.$off("roadList");
      bus.$off("eventList");
      bus.$off("carList");
      bus.$off("perception");
      bus.$off("schedul");
      this.wss2.onclose();
    },
send() {
      if (this.wss2) {
        this.infoFn();
      }
      this.wss2 = this.initWebSocket();
      this.wss2.onmessage = (data) => {
        let dataObj = JSON.parse(data.data);
        this._freshTodo({ data: dataObj });
      };
    },
相关推荐
游戏开发爱好者81 天前
iOS重构期调试实战:架构升级中的性能与数据保障策略
websocket·网络协议·tcp/ip·http·网络安全·https·udp
却道天凉_好个秋1 天前
音视频学习(三十六):websocket协议总结
websocket·音视频
2501_916013742 天前
iOS 多线程导致接口乱序?抓包还原 + 请求调度优化实战
websocket·网络协议·tcp/ip·http·网络安全·https·udp
夏天想2 天前
优化 WebSocket 实现单例连接用于打印【待测试 】
网络·websocket·网络协议
2501_915921432 天前
Fiddler 中文版怎么配合 Postman 与 Wireshark 做多环境接口调试?
websocket·网络协议·tcp/ip·http·网络安全·https·udp
游戏开发爱好者83 天前
iOS App首次启动请求异常调试:一次冷启动链路抓包与初始化流程修复
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_915106323 天前
频繁迭代下完成iOS App应用上架App Store:一次快速交付项目的完整回顾
websocket·网络协议·tcp/ip·http·网络安全·https·udp
00后程序员张3 天前
免Mac上架实战:全平台iOS App上架流程的工具协作经验
websocket·网络协议·tcp/ip·http·网络安全·https·udp
某公司摸鱼前端3 天前
uniapp socket 封装 (可拿去直接用)
前端·javascript·websocket·uni-app
2501_915921433 天前
iOS IPA 混淆实测分析:从逆向视角验证加固效果与防护流程
websocket·网络协议·tcp/ip·http·网络安全·https·udp