Vue使用socket实现实时通信

07-12 1856阅读

一、新建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();
Vue使用socket实现实时通信
(图片来源网络,侵删)
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]