Vue使用socket实现实时通信

2024-07-12 1859阅读

一、新建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购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]