vue中连接后台的websocket的http协议,心跳机制的处理

本文介绍了在Vue.js应用中如何建立与后台的WebSocket连接,并实现心跳机制和断线重连功能。详细讲解了连接后台的地址设置、心跳检测的时间间隔以及心跳失败后的唤醒和重连策略,旨在确保数据通道的稳定畅通。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端心跳机制



前言


一、连接后台的地址

VUE_APP_BASE_URL_WEBSOCKET=http://localhost:8080/imServer/
var webSocketUrl = process.env.VUE_APP_BASE_URL_WEBSOCKET;//websocket连接地址

二、创建心跳机制的时间和死亡唤醒时间

1.创建变量声明

代码如下:

 warningInfoWebSocket: {
        lockReconnect: false, // 是否允许重新连接
        timeout: 10000, // 心跳间隔
        reTimeout: 10000, // 重连间隔
        timeoutTimer: null, // 心跳定时器
        reTimeoutTimer: null, // 重连定时器
        webSocket: null
      },

2.创建websocket

代码如下(示例):

created() {
    this.getMeteorologicalRiskWarningInfoTimely();
  },
   getMeteorologicalRiskWarningInfoTimely() {
      this.createWebSocket();
    },
createWebSocket() {
      let that = this;
      let socketUrl = webSocketUrl + JSON.parse(sessionStorage.getItem("token")).uuid
      socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
      that.warningInfoWebSocket.webSocket = new WebSocket(socketUrl)
      let webSocket = that.warningInfoWebSocket.webSocket;
      webSocket.onopen = function () {
        console.log('连接成功...')
        that.heartCheckStart()
      }
      webSocket.onerror = function () {
        console.log('连接失败...')
        that.reConnect()
      }
      webSocket.onmessage = function (event) {
        that.hiddenPointMessage = JSON.parse(event.data)
        if (that.hiddenPointMessage.kind==='fast_report'){
          that.$refs.meteorological.meteorologicalInfo=that.hiddenPointMessage
          // console.log(that.$refs.meteorological.meteorologicalInfo)
          that.flightRange(that.hiddenPointMessage.kind);
        }else if (that.hiddenPointMessage.kind==='weather_report'){
          let newData =[];
          newData.push(that.hiddenPointMessage);
          that.totalNum = newData.length
          that.meteorologicalWarning(that.hiddenPointMessage.kind);
        }
        that.heartCheckReset()
      }
      webSocket.onclose = function (event) {
        console.log('连接已关闭...')
        console.log('websocket 断开: ' + event.code + ' ' + event.reason + ' ' + event.wasClean)
        that.reConnect()
      }
    },

该处使用的url网络请求的数据。

3.心跳机制的检测

heartCheckStart() {
      let that = this;
      let webSocket = that.warningInfoWebSocket.webSocket;
      let timeoutTimer = that.warningInfoWebSocket.timeoutTimer;
      let timeout = that.warningInfoWebSocket.timeout;
      timeoutTimer = setTimeout(function () {
        webSocket.send('HeartBeat')
      }, timeout)
    },

4.重新开启心跳监测机制

heartCheckReset() {
      let that = this;
      let timeoutTimer = that.warningInfoWebSocket.timeoutTimer;
      clearTimeout(timeoutTimer)
      that.heartCheckStart();
    },

4.websocket重连

reConnect() {
      let that = this;
      let lockReconnect = that.warningInfoWebSocket.lockReconnect;
      let reTimeoutTimer = that.warningInfoWebSocket.reTimeoutTimer;
      let reTimeout = that.warningInfoWebSocket.reTimeout;
      if (lockReconnect) {
        return
      }
      lockReconnect = true
      // 没连接上会一直重连,设置延迟避免请求过多
      reTimeoutTimer && clearTimeout(reTimeoutTimer)
      reTimeoutTimer = setTimeout(function () {
        that.createWebSocket();
        lockReconnect = false;
      }, reTimeout)
    },

总结

提示:这里对文章进行总结:

在消息队列中,使用http连接中后台中推送的数据必须是进行传递打开的通道,防止通道的堵塞一定要精心改时间的检测。

### Vue 前端通过 WebSocket 实现公告推送功能 在 Vue 项目中实现基于 WebSocket 的公告推送功能,可以通过以下方式完成: #### 后台消息推送机制概述 WebSocket 提供了一种全双工通信协议,允许服务器向客户端主动推送数据。这种特性非常适合实现实时更新的功能,比如公告推送[^5]。 #### Vue 前端 WebSocket 配置示例 以下是 Vue 前端配置 WebSocket 进行公告推送的具体代码示例: ```javascript <template> <div> <h1>公告推送</h1> <ul id="messages"> <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li> </ul> </div> </template> <script> export default { data() { return { websocket: null, messages: [], }; }, created() { this.initWebSocket(); }, destroyed() { this.websocket.close(); // 销毁 WebSocket 连接 }, methods: { initWebSocket() { const userName = 'guest'; // 用户名可以根据实际需求动态设置 this.websocket = new WebSocket(`ws://localhost:8801/myproject/websocket/${userName}`); // 替换为实际的 WebSocket URL[^3] this.websocket.onopen = () => { console.log('WebSocket连接'); }; this.websocket.onerror = (error) => { console.error('WebSocket 发生错误:', error); }; this.websocket.onmessage = (event) => { const message = event.data; this.messages.push(message); // 将新消息推入列表 console.log('收到新的公告:', message); }; this.websocket.onclose = () => { console.log('WebSocket 已断开'); }; }, }, }; </script> <style scoped> #messages li { list-style-type: none; } </style> ``` 上述代码展示了如何在 Vue 组件中初始化 WebSocket,并处理 `onopen`、`onmessage` 和 `onclose` 等事件[^2]。 #### Java Spring Boot 后端 WebSocket 配置示例 如果后端采用的是 Spring Boot,则可以按照以下方式进行 WebSocket 配置: ##### 创建 WebSocket 配置类 ```java import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new AnnouncementHandler(), "/websocket/{username}").setAllowedOrigins("*"); } } ``` ##### 自定义 WebSocket 处理器 ```java import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; @Component public class AnnouncementHandler extends TextWebSocketHandler { private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { String payload = message.getPayload(); broadcast(payload); // 推送消息给所有已连接的客户端 } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } public void broadcast(String announcement) { for (WebSocketSession session : sessions) { try { if (session.isOpen()) { session.sendMessage(new TextMessage(announcement)); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 以上代码实现了 WebSocket 的基本逻辑以及广播消息的功能。 #### 注意事项 - **跨域问题**:确保前后端之间的 CORS 设置正确,避免因跨域限制导致 WebSocket 连接失败。 - **心跳检测**:为了保持 WebSocket 连接稳定,建议加入心跳机制定期检测连接状态。 - **异常处理**:对于网络中断或其他意外情况,应设计合理的重连策略。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小仙有礼了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值