前端js react 全局websocket 连接类 带订阅发布以及使用方法

连接websocket js类,整合聚合发布,其它任意文件进行订阅


//@ts-ignore
import {
    toLogin } from '@/utils/login';
import {
    message } from 'antd';
//@ts-ignore
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
let userId = localStorage.getItem('userId')

interface subscribes {
   
  name: string,
  subscribe: any
}

export class WS {
   

  //链接地址
  socketAddress: string = APP_URL.socketAddress;
  stompClient: any = null;
  socket: any = null;
  messageData: any[] = [];
  conCount: number = 0;
  timerCon: any = null;
  timerStomp:any = null;
  stompCount:number = 0;
  connected: boolean = false;
  subscribeFuns: Map<Function, Function> = new Map();
  subscribes: subscribes[] = []; //{name:'message',subscribe:subscribeFun}
  //链接地址
  urls: {
    name: string, url: string }[] = [
    {
    name: 'message', url: `/user/${
     userId}/topic/message` }, //基地变更消息
    {
    name: 'overTimeMessage', url: `/user/${
     userId}/topic/token/expiration` }, // 离线消息
    {
    name: 'dropLineMessage', url: `/user/${
     userId}/topic/login/repeat` }, // 下线
    {
    name: 'storageMessage', url: `/topic/Storage/message` },  //入库申请
    {
    name: 'chatMessage', url: `/user/${
     userId}/topic/chat` },//聊天消息
  ]

  constructor() {
   
    this.connectWs();

  }

  /**
   * 订阅消息
   * @param fn
   */
  subscribeMessage(fn: Function) {
   
    this.subscribeFuns.set(fn, fn)
  }

  //订阅所有
  subscribeAll(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值