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>
相关推荐
我是日安1 小时前
从零到一打造 Vue3 响应式系统 Day 10 - 为何 Effect 会被指数级触发?
前端·vue.js
艾小码1 小时前
还在硬邦邦跳转页面?Vue这3招让应用丝滑如德芙!
前端·javascript·vue.js
Olrookie2 小时前
ruoyi-vue(十五)——布局设置,导航栏,侧边栏,顶部栏
前端·vue.js·笔记
召摇2 小时前
API 设计最佳实践 Javascript 篇
前端·javascript·vue.js
码间舞2 小时前
文件太大怎么上传?【分组分片上传大文件】-实战记录
前端·vue.js·程序员
鹏多多3 小时前
基于Vue3+TS的自定义指令开发与业务场景应用
前端·javascript·vue.js
gnip12 小时前
企业级配置式表单组件封装
前端·javascript·vue.js
王王碎冰冰18 小时前
基于 Vue3@3.5+跟Ant Design of Vue 的二次封装的 Form跟搜索Table
前端·vue.js
天蓝色的鱼鱼19 小时前
Element UI 2.X 主题定制完整指南:解决官方工具失效的实战方案
前端·vue.js
我是日安20 小时前
从零到一打造 Vue3 响应式系统 Day 8 - Effect:深入剖析嵌套 effect
前端·vue.js