Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 websocket封装

作者:我说°走了就别回来   发布日期:2026-07-27   浏览:46

// Vue3 WebSocket 封装示例

import { ref, onMounted, onUnmounted } from 'vue';

class WebSocketService {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.isAlive = false;
    this.reconnectInterval = 3000; // 重连间隔时间,单位为毫秒
    this.reconnectAttempts = 0; // 重连尝试次数
    this.maxReconnectAttempts = 5; // 最大重连尝试次数
  }

  connect() {
    this.socket = new WebSocket(this.url);
    this.isAlive = true;

    this.socket.onopen = () => {
      console.log('WebSocket connection established');
      this.reconnectAttempts = 0; // 重连成功后重置重连次数
    };

    this.socket.onmessage = (event) => {
      console.log('Received message:', event.data);
      // 处理接收到的消息
    };

    this.socket.onclose = () => {
      console.log('WebSocket connection closed');
      this.isAlive = false;
      this.reconnect();
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error:', error);
      this.isAlive = false;
      this.reconnect();
    };
  }

  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      setTimeout(() => {
        this.connect();
      }, this.reconnectInterval);
    } else {
      console.error('Max reconnect attempts reached');
    }
  }

  send(message) {
    if (this.isAlive && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
      console.log('Message sent:', message);
    } else {
      console.error('WebSocket is not open. Ready state:', this.socket.readyState);
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
      this.isAlive = false;
    }
  }
}

export function useWebSocket(url) {
  const messages = ref([]);
  const wsService = new WebSocketService(url);

  const initWebSocket = () => {
    wsService.connect();

    wsService.socket.onmessage = (event) => {
      messages.value.push(event.data);
    };
  };

  onMounted(() => {
    initWebSocket();
  });

  onUnmounted(() => {
    wsService.close();
  });

  return {
    messages,
    send: (message) => wsService.send(message),
  };
}

解释说明:

  1. WebSocketService 类

    • constructor(url):初始化 WebSocket 的 URL 和其他配置。
    • connect():创建 WebSocket 连接,并处理连接成功、消息接收、连接关闭和错误事件。
    • reconnect():当连接断开时尝试重新连接,最多尝试 maxReconnectAttempts 次。
    • send(message):发送消息到服务器。
    • close():关闭 WebSocket 连接。
  2. useWebSocket 函数

    • 使用 Vue3 的 Composition API 来封装 WebSocket 功能。
    • initWebSocket():初始化 WebSocket 连接并监听消息。
    • onMounted()onUnmounted():分别在组件挂载和卸载时启动和关闭 WebSocket。
    • 返回 messagessend 方法供外部使用。

上一篇:vue数组删除指定位置元素

下一篇:vue3 foreach

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js transpi

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站