搞一下常用的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 });
      };
    },
相关推荐
小范同学_4 小时前
Spring集成WebSocket
java·spring boot·websocket·spring·1024程序员节
YUELEI1182 天前
Springboot WebSocket
spring boot·后端·websocket
Greedy Alg5 天前
Socket编程学习记录
网络·websocket·学习
Cxiaomu5 天前
React Native 项目中 WebSocket 的完整实现方案
websocket·react native·react.js
Arva .6 天前
WebSocket实现网站点赞通知
网络·websocket·网络协议
火星数据-Tina6 天前
LOL实时数据推送技术揭秘:WebSocket在电竞中的应用
网络·websocket·网络协议
paopaokaka_luck6 天前
基于SpringBoot+Vue的社区诊所管理系统(AI问答、webSocket实时聊天、Echarts图形化分析)
vue.js·人工智能·spring boot·后端·websocket
歪歪1006 天前
使用 Wireshark 进行 HTTP、MQTT、WebSocket 抓包的详细教程
网络·websocket·测试工具·http·wireshark
EndingCoder7 天前
WebSocket实时通信:Socket.io
服务器·javascript·网络·websocket·网络协议·node.js
J_bean7 天前
Spring Boot 集成 WebSocket 的实战案例
spring boot·websocket