Vue使用socket实现实时通信

一、新建socket文件

class SocketService {
  constructor() {
    this.socket = null;
    this.reconnectTimer = null;
    this.messageCallback = null;
    this.connectionParams = null;
    this.path=null
  }

  init() {
    this.clearReconnectTimer(); // 尝试重新连接之前先清除重连定时器


    if (typeof WebSocket === "undefined") {
      throw new Error("您的浏览器不支持WebSocket");
    }


    this.socket = new WebSocket(this.path);
    this.socket.addEventListener("open", this.open.bind(this));
    this.socket.addEventListener("error", this.error.bind(this));
    this.socket.addEventListener("close", this.close.bind(this));
    this.socket.addEventListener("message", this.getMessage.bind(this));
  }
  open() {
    console.log('%c [ WebSocket已连接 ]', 'font-size:16px; background:#7fce50; color:white;')
    this.clearReconnectTimer();
  }

  close(event) {
    console.log('%c [ WebSocket已关闭并断开连接 ]', 'font-size:16px; background:red; color:white;')
    this.destroyWebsocket();
  }

  error(event) {
    console.log('%c [ WebSocket已断开连接 ]', 'font-size:16px; background:red; color:white;')
    this.startReconnectTimer();

  }

  getMessage(event) {
    if (event.data === "连接成功") {
      return;
    }
    const message = event.data;
    if (this.messageCallback) {
      this.messageCallback(message);
    }
  }

  startReconnectTimer() {

    if (!this.reconnectTimer) {

      this.reconnectTimer = setInterval(() => {
        console.log('%c [ WebSocket已断开 尝试重新连接... ]', 'font-size:16px; background:red; color:white;')
        if (this.connectionParams) {
          this.init();
        }
      }, 3000); // 重连间隔为 3 秒
    }
  }

  clearReconnectTimer() {
    if (this.reconnectTimer) {
      clearInterval(this.reconnectTimer);
      this.reconnectTimer = null;
      this.clearReconnectTimer();
    }
  }

  destroyWebsocket() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
      this.clearReconnectTimer();
      this.messageCallback = null; // 或者清除 messageCallback 的引用
    }
  }
}

const socketService = new SocketService();
export default socketService;

二、引入并调用

//引入
import socketService from "./socket.js";
//开启
initSocketService() {
			// const id = '';
			const path = `${Monitor_Alarm}${this.tenantId}/${this.userInfo.id}`;
			// const path =
			// 	"ws://aes.aes-iot.com:8301/sys-alarm/ws/dashboard/admin/d35fd488525686145aca387b0158c234";
			// let url = .replace(/^https?:\/\//g, "");
			// const path = `ws://${url}/sys-alarm/ws/dashboard/802/10000`;
			// const type = "device";
			// 初始化 WebSocket 连接 传递类型 设备id
			socketService.path = path;
			socketService.init();
			socketService.messageCallback = this.handleMessage;
		},
//接收消息后的处理
handleMessage(message) {}
//关闭
this.closeWebsocket();

相关推荐

  1. Vue使用socket实现实时通信

    2024-07-12 15:42:04       26 阅读
  2. vue2 使用 Socket.io 实现 WebSocket

    2024-07-12 15:42:04       24 阅读
  3. socket编程实现TCP通信

    2024-07-12 15:42:04       33 阅读
  4. socket通信实现TCP协议的同步通信

    2024-07-12 15:42:04       53 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 15:42:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 15:42:04       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 15:42:04       58 阅读
  4. Python语言-面向对象

    2024-07-12 15:42:04       69 阅读

热门阅读

  1. golang使用migrate迁移pg数据库表报错处理

    2024-07-12 15:42:04       23 阅读
  2. C#,开发过程中技术点GPT问答记录

    2024-07-12 15:42:04       19 阅读
  3. 学生管理系统(残缺版)

    2024-07-12 15:42:04       22 阅读
  4. IPython多核并行编程指南:并发任务处理

    2024-07-12 15:42:04       22 阅读
  5. 【LeetCode】快乐数

    2024-07-12 15:42:04       22 阅读
  6. 数据分析如何正确地学习与使用

    2024-07-12 15:42:04       21 阅读
  7. MySQL 常用功能

    2024-07-12 15:42:04       25 阅读
  8. keep-alive缓存组件

    2024-07-12 15:42:04       19 阅读