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>
相关推荐
网络点点滴37 分钟前
Vue如何处理数据、v-HTML的使用及总结
前端·vue.js·html
00后程序员张37 分钟前
调试 WebView 接口时间戳签名问题:一次精细化排查和修复过程
websocket·网络协议·tcp/ip·http·网络安全·https·udp
世界哪有真情41 分钟前
用虚拟IP扩容端口池:解决高并发WebSocket端口耗尽问题
前端·后端·websocket
好名字更能让你们记住我41 分钟前
Linux多线程(十二)之【生产者消费者模型】
linux·运维·服务器·jvm·windows·centos
门思科技43 分钟前
设计可靠 LoRaWAN 设备时需要考虑的关键能力
运维·服务器·网络·嵌入式硬件·物联网
小锋学长生活大爆炸1 小时前
【知识】RPC和gRPC
服务器·网络协议·rpc
学习编程的gas1 小时前
Linux开发工具——gcc/g++
linux·运维·服务器
大大。1 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
paopaokaka_luck1 小时前
基于SpringBoot+Vue的酒类仓储管理系统
数据库·vue.js·spring boot·后端·小程序
_可乐无糖1 小时前
AWS WebRTC: 判断viewer端拉流是否稳定的算法
linux·服务器·webrtc·aws