Socket.io Client: respond to all events with one handler?

前端 未结 14 1931
时光取名叫无心
时光取名叫无心 2020-11-28 04:16

Is it possible to have a socket.io client respond to all events without to have specify each event individually?

For example, something like this (which obviously do

14条回答
  •  北海茫月
    2020-11-28 04:56

    I'm using Angular 6 and the npm package: ngx-socket-io

    import { Socket } from "ngx-socket-io";
    

    ...

    constructor(private socket: Socket) { }
    

    ...

    After connect the socket, I use this code, this is handling all custom events...

    const onevent = this.socket.ioSocket.onevent;
    this.socket.ioSocket.onevent = function (packet: any) {
      const args = packet.data || [];
      onevent.call(this, packet);    // original call
      packet.data = ["*"].concat(args);
      onevent.call(this, packet);      // additional call to catch-all
    };
    this.socket.on("*", (eventName: string, data: any) => {
      if (typeof data === 'object') {
        console.log(`socket.io event: [${eventName}] -> data: [${JSON.stringify(data)}]`);
      } else {
        console.log(`socket.io event: [${eventName}] -> data: [${data}]`);
      }
    });
    

提交回复
热议问题