搞一下常用的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 });
      };
    },
相关推荐
李小狼lee10 小时前
websocket的理解,写一个在线聊天室
websocket
阿萨德528号13 小时前
Spring Boot + WebSocket超简单实战源码(前后端实时交互)
spring boot·websocket·交互
CryptoRzz1 天前
印度尼西亚(IDX)股票数据对接开发
java·后端·websocket·web3·区块链
mudtools2 天前
飞书 .NET SDK 事件处理的幂等性与去重机制
websocket·.net·飞书·webhook
weixin79893765432...2 天前
深入浅出 WebSocket 协议
websocket·http·socket·sse
callJJ2 天前
WebSocket 两种实现方式对比与入门
java·python·websocket·网络协议·stomp
今晚务必早点睡2 天前
系统通信方式实战详解:HTTP、RPC、MQ、WebSocket 各用在什么场景?(附 SDK 示例)
websocket·http·rpc
*才华有限公司*2 天前
RTSP视频流播放系统
java·git·websocket·网络协议·信息与通信
栗子叶2 天前
网页接收服务端消息的几种方式
前端·websocket·http·通信
栗子叶3 天前
SSE、长轮询与 WebSocket 连接资源对比及 Spring Boot 配置指南
spring boot·websocket·网络协议