搞一下常用的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 });
      };
    },
相关推荐
sunshine__sun4 天前
JMeter 测试 WebSocket 接口的详细教程
websocket·网络协议·jmeter
bkspiderx4 天前
libwebsockets 服务端获取过代理的真实连接IP
websocket·libwebsockets·过代理的真实连接ip
阿松のblog6 天前
vue3+ts+flask+websocket实现实时异物检测
python·websocket·flask
码侯烧酒9 天前
前端视角下关于 WebSocket 的简单理解
前端·websocket·网络协议
zhoupenghui1689 天前
golang实现支持100万个并发连接(例如,HTTP长连接或WebSocket连接)系统架构设计详解
开发语言·后端·websocket·golang·系统架构·echo·100万并发
小粽子编程11 天前
Pig Cloud遇到websocket不能实现同一个用户不同浏览器接受到广播的消息解决方案
网络·websocket·网络协议
小毛驴85011 天前
WebSocket 在多线程环境下处理 Session并发
网络·websocket·网络协议
yuyu_030412 天前
电子秤利用Websocket做为Client向MES系统推送数据
网络·websocket·网络协议
二闹13 天前
实时数据触手可及!前端开发者必看的连接指南
前端·websocket