vue2 ruoyi websocket轮询

news/2025/2/26 7:52:20

文章目录

  • 前言
  • 一、websocket和心跳是什么?
  • 二、使用步骤
    • 1.
    • 2.监听变化
    • 3.关闭
  • 总结


前言

websocket,实现与后端通讯,使用心跳机制,断联自动恢复。


websocket_11">一、websocket和心跳是什么?

  1. WebSocket
    WebSocket 是一种网络通信协议,允许客户端和服务器之间进行全双工通信(即双方可以同时发送和接收数据)。它通过一次 HTTP 握手建立连接,之后保持长连接,适合实时性要求高的场景。

  2. 心跳机制(Heartbeat)
    心跳机制是一种用于检测连接是否存活的机制。客户端和服务器通过定期发送小型数据包(称为“心跳包”)来确认对方是否在线。
    实现方式:
    客户端和服务器约定一个时间间隔(如 30 秒)。
    客户端定期向服务器发送心跳包(通常是一个小型数据包,如 ping)。
    服务器收到心跳包后回复一个响应包(如 pong)。
    如果一方在指定时间内未收到心跳包或响应包,则认为连接已断开。

二、使用步骤

1.

代码如下(示例):

  created() {
    const self = this; // 在这里保存组件实例的引用
    this.join();
    clearInterval(this.setIntervalId);
    this.setIntervalId=setInterval(()=>{
      // 使用 setTimeout 来创建延迟
        this.heartbeatTest();
    },3000)
  },
		//开始链结
   join() {
      const wsuri = this.url;//url地址wss://127.0.0.1:1234/websocket/message
      const self = this;
      this.ws = new WebSocket(wsuri);
      this.ws.onopen = function (event) {
        self.text_state = self.text_state + "已经打开连接!" + "\n";
        clearTimeout(this.heartSetTimeOutId)
      };
      this.ws.onmessage = function (event) {
        self.waitingResponse = true;
        self.text_content = event.data;
        self.message = event.data;
        if (self.text_content == "ok"){
          self.sendHandle("停机维护")
        }
      };
      this.ws.onclose = (event) => {
        // 处理连接关闭事件,例如重新连接或执行其他操作
        if (this.reConnectNum < 10){
       this.heartSetTimeOutId = setTimeout(() => {
          this.join();
          this.reConnectNum++;
        }, 20000); // 根据需要调整延迟的持续时间(以毫秒为单位)
        }
      };
      this.ws.onerror = (error) => {
        console.error('WebSocket error: ', error);
        // 处理WebSocket错误事件
      };
    },
    exit() {
      if (this.ws) {
        clearInterval(this.setIntervalId);
        this.ws = null;
      }
    },
    heartbeatTest(){
      if (this.ws.readyState !== WebSocket.CLOSED){
        this.sendMessage = "heartCheck";
        this.ws.send(this.sendMessage);
      }
    },
    close() {
      const self = this;
      if (this.ws && this.ws.OPEN){
        this.ws.onclose = function (event) {
          self.text_state = self.text_state + "已经关闭连接!" + "\n";
        };
      }

    },

2.监听变化


  watch:{
    text_content:{
        deep:true,
      handler(n,o){
            if (n.indexOf('opera') >-1){
              let json = JSON.parse(n);
              this.noticeShowFlag = json.maintainStatus;
              this.noticeShowMsg = "";
              if (this.noticeShowFlag){
                this.noticeShowMsg = json.expirseTime+"操作!!";
              }
            }
      }
    }
  },

3.关闭

  beforeDestroy() {
    //页面销毁时关闭长连接
    this.close();
    this.exit();
  },

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。


http://www.niftyadmin.cn/n/5868337.html

相关文章

JSP+Servlet 实现分页(Tomcat 9)

访问地址 项目路径/mulPageSystem java文件&#xff1b;包名org.rain.bean 文件名 PageSystemBean package org.rain.bean; public class PageSystemBean { private String school; private String home; public String getSchool() { return school; } public void s…

Vue的项目创建以及项目目录与组合式API

一.创建Vue 1.Vue-CLI:创建Vue的脚手架工具 2.Create-vue&#xff1a;是Vue官方提供的脚手架之一,底层采用官方自主研发的vite,快捷&#xff0c;开发方便。 3.准备工作:系统中需要安装nodejs环境&#xff0c;在该环境中提供npm包管理器 4.创建Vue项目的命令:npm init vuela…

最新前端框架选型对比与建议(React/Vue/Svelte/Angular)

前端框架选型对比与建议&#xff08;React/Vue/Svelte/Angular&#xff09; 一、核心框架技术特性对比&#xff08;基于最新版本&#xff09; 维度React 19 25Vue 3.5 12Svelte 5 25Angular 19 5核心理念函数式编程、JSX语法、虚拟DOM渐进式框架、组合式API、模板语法编译时框…

SQL注入(order by,limit),seacms的报错注入以及系统库的绕过

1&#xff1a;如果information_schema被过滤了&#xff0c;该怎么绕过 1.1&#xff1a;介绍一下information_schema这个库 information_schema 是一个非常重要的系统数据库&#xff0c;它在SQL标准中定义&#xff0c;并且被许多关系型数据库管理系统&#xff08;RDBMS&#x…

音视频编码和封装格式

文章目录 音视频编码格式音频编码视频编码 音视频封装格式 音视频编码格式 音频编码 音频编码是一种将音频信号转换为数字形式的过程&#xff0c;目的是减少数据中的冗余&#xff0c;以便存储和传输。 音频编码的实质是通过抽样、量化和编码三个步骤&#xff0c;将连续变化的…

爬虫运行后如何保存数据?

爬虫运行后&#xff0c;将获取到的数据保存到本地或数据库中是常见的需求。Python 提供了多种方式来保存数据&#xff0c;包括保存为文本文件、CSV 文件、JSON 文件&#xff0c;甚至存储到数据库中。以下是几种常见的数据保存方法&#xff0c;以及对应的代码示例。 1. 保存为文…

class绑定和style绑定

class绑定 简单对象绑定 <template> <div><p :class"{active:isActive,text-danger:hasError}">Class样式绑定1</p> </div> </template> <script> export default{data(){return{isActive:true,hasError:true,}} } <…

python-leetcode-每日温度

739. 每日温度 - 力扣&#xff08;LeetCode&#xff09; class Solution:def dailyTemperatures(self, temperatures: List[int]) -> List[int]:n len(temperatures)answer [0] * nstack [] # 存储索引for i, temp in enumerate(temperatures):while stack and temperat…