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

前端 未结 14 1881
时光取名叫无心
时光取名叫无心 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:55

    All methods I found (including socket.io-wildcard and socketio-wildcard) didn't work for me. Apparently there is no $emit in socket.io 1.3.5...

    After reading socket.io code, I patched up the following which DID work:

    var Emitter = require('events').EventEmitter;
    var emit = Emitter.prototype.emit;
    [...]
    var onevent = socket.onevent;
    socket.onevent = function (packet) {
        var args = ["*"].concat (packet.data || []);
        onevent.call (this, packet);    // original call
        emit.apply   (this, args);      // additional call to catch-all
    };
    

    This might be a solution for others as well. However, ATM I don't exactly understand why nobody else seems to have issues with the existing "solutions"?!? Any ideas? Maybe it's my old node version (0.10.31)...

    0 讨论(0)
  • 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}]`);
      }
    });
    
    0 讨论(0)
提交回复
热议问题