Vue 如何使用WebSocket与服务器建立链接 持续保持通信

WebSocket

浏览器通过JavaScript向服务器发出建立WebSocket链接的请求,链接建立后,客户端和服务器端就可以通过TCP链接直接交互数据。WebSocket链接后可以通过send()方法来向服务器发送数据,并通过onnessage事件来接受服务器返回的数据。

创建WebSocket对象

复制代码
let ws = new WebSocket(server);

WebSocket参考

WebSocket - Web API 接口参考 | MDN

代码

javascript 复制代码
<template>
  <el-row class="app-container">
    <el-button type="primary" @click="testSend">主要按钮</el-button>
  </el-row>
</template>

<script>

export default {
  name: 'Monitoring',
  data() {
    return {
      websocket: null, // WebSocket对象
      reconnectInterval: 3000, // 重连间隔时间(毫秒)
      restartWebsocket: null , // 重启定时器
      heartbeatInterval: null, // 心跳定时器
    };
  },
  created() {
    if (typeof WebSocket == "undefined") {
      console.log("您的浏览器不支持WebSocket");
    } else {
      this.setupWebSocket(); // 创建WebSocket连接
    }
  },
  methods: {
    testSend() { // 测试
      const send = {
        "keywords": "xxx",
        }
      this.sendMessage(JSON.stringify(send));
    },
    // websocket初始化
    setupWebSocket() {
      this.websocket = new WebSocket("ws://xxx"); // 创建WebSocket连接
      this.websocket.onopen = this.onWebSocketOpen; // WebSocket连接打开时的处理函数
      this.websocket.onmessage = this.onWebSocketMessage; // 收到WebSocket消息时的处理函数
      this.websocket.onclose = this.onWebSocketClose; // WebSocket连接关闭时的处理函数
    },
    closeWebSocket() { // 关闭
      if (this.websocket) {
        this.websocket.close(); // 关闭WebSocket连接
      }
    },
    // 开启 WebSocket;启动心跳检测
    onWebSocketOpen() {
      console.log("WebSocket connection is open");
      this.startHeartbeat();
    },
    // 处理从服务器接收的消息
    onWebSocketMessage(event) {
      if (event.data) {
        const message = JSON.parse(event.data);
        //    根据业务来处理数据
        console.log("Message from server ", message);
      }
    },
    // 关闭 WebSocket;停止心跳检测
    onWebSocketClose() {
      console.log("WebSocket connection is closed");
      this.stopHeartbeat(); // WebSocket连接关闭时,停止心跳检测
      this.restartWebsocket = setTimeout(this.setupWebSocket, this.reconnectInterval); // 在一定时间后重连WebSocket
    },
    // 向服务器发送消息
    sendMessage(message) {
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(message); // 发送消息到WebSocket服务器
      }
    },
    // 开启心跳检测
    startHeartbeat() {
      this.heartbeatInterval = setInterval(() => {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
          this.websocket.send(); // 发送心跳消息
        }
      }, 1000); // 每1秒发送一次心跳
    },
    // 停止心跳检测
    stopHeartbeat() {
      if (this.heartbeatInterval) {
        clearInterval(this.heartbeatInterval); // 停止心跳检测定时器
      }
    },
    // 停止重启检测
    stopRestartWebsocket() {
      if (this.restartWebsocket) {
        clearInterval(this.restartWebsocket); // 停止心跳检测定时器
      }
    },
  },
  beforeDestroy() {
    this.stopHeartbeat() // 停止心跳
    this.stopRestartWebsocket() // 停止重启
    this.closeWebSocket(); // 在组件销毁前关闭WebSocket连接
  },
}
</script>

<style scoped>

</style>
相关推荐
pepedd86437 分钟前
还在开发vue2老项目吗?本文带你梳理vue版本区别
前端·vue.js·trae
前端缘梦1 小时前
深入理解 Vue 中的虚拟 DOM:原理与实战价值
前端·vue.js·面试
HWL56791 小时前
pnpm(Performant npm)的安装
前端·vue.js·npm·node.js
檀越剑指大厂2 小时前
【Linux系列】如何在 Linux 服务器上快速获取公网
linux·服务器·php
共享家95272 小时前
linux-高级IO(上)
java·linux·服务器
柯南95272 小时前
Vue 3 reactive.ts 源码理解
vue.js
柯南95272 小时前
Vue 3 Ref 源码解析
vue.js
小高0072 小时前
面试官:npm run build 到底干了什么?从 package.json 到 dist 的 7 步拆解
前端·javascript·vue.js
JayceM3 小时前
Vue中v-show与v-if的区别
前端·javascript·vue.js
HWL56793 小时前
“preinstall“: “npx only-allow pnpm“
运维·服务器·前端·javascript·vue.js