搞一下常用的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 });
      };
    },
相关推荐
LuckyRich124 分钟前
【websocket】安装与使用
网络·websocket·网络协议
椰椰椰耶11 小时前
[网页五子棋][匹配模块]实现胜负判定,处理玩家掉线
java·开发语言·spring boot·websocket·spring
言之。1 天前
Tornado WebSocket实时聊天实例
python·websocket·tornado
00后程序员张2 天前
移动网页调试的多元路径:WebDebugX 与其他调试工具的组合使用策略
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_916013742 天前
iOS 应用如何防止源码与资源被轻易还原?多维度混淆策略与实战工具盘点(含 Ipa Guard)
websocket·网络协议·tcp/ip·http·网络安全·https·udp
行云流水剑2 天前
【学习记录】Django Channels + WebSocket 异步推流开发常用命令汇总
redis·websocket·学习·django
椰椰椰耶2 天前
[网页五子棋][对战模块]实现游戏房间页面,服务器开发(创建落子请求/响应对象)
服务器·websocket·spring
佩奇的技术笔记3 天前
WebSocket与Reactor模式:构建实时交互应用
websocket·网络协议
椰椰椰耶4 天前
[网页五子棋][匹配模块]处理开始匹配/停止匹配请求(匹配算法,匹配器的实现)
java·python·websocket·spring·java-ee