webscoket使用

73 阅读3分钟

websocket.ts文件

import emitter from '@/hooks/component/useEventBus';
import { ElNotification } from 'element-plus';
import { CloseBold } from '@element-plus/icons-vue';
import { getToken } from '@/utils/auth';
// 初始化socket
export const initWebSocket = (url: any) => {
  if (import.meta.env.VITE_APP_WEBSOCKET === 'false') {
    return;
  }
  // 获取token

  // 创建WebSocket连接选项
  const wsOptions = {
    autoReconnect: {
      // 重连最大次数
      retries: -1,
      // 重连间隔
      delay: 1000,
      onFailed() {
        console.log('websocket重连失败');
      }
    },
    heartbeat: {
      message: JSON.stringify({ cmd: 'ping' }),
      // 发送心跳的间隔
      interval: 5000,
      // 接收到心跳response的超时时间
      pongTimeout: 3000
    },
    onConnected() {
      console.log('websocket已经连接');
    },
    onError() {
      console.log('websocket错误');
    },
    onMessage: (_, e) => {
      console.log('websocket收到消息', e);
      // if (e.indexOf('ping') > 0) {
      //   return;
      // }
      const msg = JSON.parse(e.data);
      switch (msg?.cmd) {
        case 'event':
          emitter.emit('event', msg);
          break;
        default:
          break;
      }
    },
    // 如果useWebSocket支持header参数,可以添加以下配置
    headers: {
      Authorization: `Bearer ${getToken()}`,
      clientid: import.meta.env.VITE_APP_CLIENT_ID
    }
  };

  // 检查环境是否支持通过header传递token
  // 如果不支持,则使用原始的URL参数方式作为备选
  if (typeof WebSocket !== 'undefined' && !('headers' in WebSocket.prototype)) {
    // 降级方案:通过URL参数传递token
    url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
    // 移除不支持的headers配置
    delete wsOptions.headers;
  }

  const { status, data, send, open } = useWebSocket(url, wsOptions);

  return { status, data, send, open };
};


APP.vue页面(调用ws,启动ws连接)

import { initWebSocket } from '@/utils/websocket';

onMounted(() => {
  const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  initWebSocket(protocol + window.location.host + import.meta.env.VITE_APP_BASE_API + '/resource/websocket');
});

使用页面

//若是使用事件总线传值,则使用事件总线直接接收
 emitter.on('message', (data) => {
   console.log(data);
 });
 
//若是在页面需要发送向后端发送信息,则调用send
  const { send } = initWebSocket(protocol + window.location.host + import.meta.env.VITE_APP_BASE_API + '/resource/websocket');
  //send发送的内容由前后端规定好
  send({
  //放所需要发送的内容,例如:下面的type和data
    type: 'init',
    data: {
      tenantId: useSettingsStore().tenantId,
      userId: useUserStore().userInfo.id
    }
  });

useEventBus.ts页面

import { mitt } from '@/utils/mitt';

const emitter = mitt();

export default emitter;

mitt.ts页面

/**
 * copy to https://github.com/developit/mitt
 * Expand clear method
 */
export type EventType = string | symbol;

// An event handler can take an optional event argument
// and should not return a value
export type Handler<T = unknown> = (event: T) => void;
export type WildcardHandler<T = Record<string, unknown>> = (type: keyof T, event: T[keyof T]) => void;

// An array of all currently registered event handlers for a type
export type EventHandlerList<T = unknown> = Array<Handler<T>>;
export type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;

// A map of event types and their corresponding event handlers.
export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<
  keyof Events | '*',
  EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>
>;

export interface Emitter<Events extends Record<EventType, unknown>> {
  all: EventHandlerMap<Events>;

  on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
  on(type: '*', handler: WildcardHandler<Events>): void;

  off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;
  off(type: '*', handler: WildcardHandler<Events>): void;

  emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
  emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
  clear(): void;
}

/**
 * Mitt: Tiny (~200b) functional event emitter / pubsub.
 * @name mitt
 * @returns {Mitt}
 */
export function mitt<Events extends Record<EventType, unknown>>(all?: EventHandlerMap<Events>): Emitter<Events> {
  type GenericEventHandler = Handler<Events[keyof Events]> | WildcardHandler<Events>;
  all = all || new Map();

  return {
    /**
     * A Map of event names to registered handler functions.
     */
    all,

    /**
     * Register an event handler for the given type.
     * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
     * @param {Function} handler Function to call in response to given event
     * @memberOf mitt
     */
    on<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {
      const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
      if (handlers) {
        handlers.push(handler);
      } else {
        all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);
      }
    },

    /**
     * Remove an event handler for the given type.
     * If `handler` is omitted, all handlers of the given type are removed.
     * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)
     * @param {Function} [handler] Handler function to remove
     * @memberOf mitt
     */
    off<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) {
      const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
      if (handlers) {
        if (handler) {
          handlers.splice(handlers.indexOf(handler) >>> 0, 1);
        } else {
          all!.set(type, []);
        }
      }
    },

    /**
     * Invoke all handlers for the given type.
     * If present, `'*'` handlers are invoked after type-matched handlers.
     *
     * Note: Manually firing '*' handlers is not supported.
     *
     * @param {string|symbol} type The event type to invoke
     * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
     * @memberOf mitt
     */
    emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {
      let handlers = all!.get(type);
      if (handlers) {
        (handlers as EventHandlerList<Events[keyof Events]>).slice().map((handler) => {
          handler(evt!);
        });
      }

      handlers = all!.get('*');
      if (handlers) {
        (handlers as WildCardEventHandlerList<Events>).slice().map((handler) => {
          handler(type, evt!);
        });
      }
    },

    /**
     * Clear all
     */
    clear() {
      this.all.clear();
    }
  };
}