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>
相关推荐
happyh h h h p p p p7 分钟前
部署DNS从服务器
运维·服务器·网络
jiunian_cn9 分钟前
【Linux】Linux权限
linux·服务器·mysql
疯狂的沙粒17 分钟前
uni-app 项目支持 vue 3.0 详解及版本升级方案?
前端·vue.js·uni-app
情系淮思33 分钟前
客户端和服务器已成功建立 TCP 连接【输出解析】
服务器·网络·tcp/ip
Lhuu(重开版1 小时前
Vue:Ajax
vue.js·ajax·okhttp
国家不保护废物1 小时前
从刀耕火种到现代框架:DOM编程 vs Vue/React 进化史
前端·vue.js·react.js
wkj0011 小时前
QuaggaJS 配置参数详解
java·linux·服务器·javascript·quaggajs
阿琳a_1 小时前
前端对WebSocket进行封装,并建立心跳监测
前端·javascript·vue.js·websocket
Am1nnn2 小时前
【Pinia】Pinia和Vuex对比
前端·javascript·vue.js
ZZZKKKRTSAE3 小时前
快速上手Linux全局搜索正则表达式(grep)
linux·服务器·正则表达式