socket.io-stream icon indicating copy to clipboard operation
socket.io-stream copied to clipboard

Any event

Open peteruithoven opened this issue 9 years ago • 0 comments

I need to forward socket.io-streams over a server (from client to another client), so I needed a way to handle any event. I already found tricks to do this with socket.io, see: https://github.com/Automattic/socket.io/issues/1715

But since socket.io-stream works differently, it for example relies on overriding the event handler the users supplies (to replace the StreamID with a actual IOStream), I had to find a different solution.

The basics of my solution:

function createAnyEvents(socket) {
  if(socket.sio && socket.$emit) {
    // listen for stream events on original socket.io socket
    socket.sio.on("stream",function() {
      var args = Array.prototype.slice.call(arguments);
      // Chanding original event to any event, 
      // adding original event type as argument
      // from: eventType, pos, streamID, data, callback
      // to: any, pos, eventType, streamID, data, callback
      // Adding original eventType after pos:
      args.splice(2,0,args[0]); 
      // Changing event type to any:
      args[0] = 'any'; 
      // Increment pos (streamID positions)
      // (because we added eventType in front of them)
      for(var i in args[1]) args[1][i]++;
      socket.$emit.apply(socket,args);
    });
  } else {
    debug("Error: Can't create 'any' event");
  }
}
createAnyEvents(ss(socket));
ss(socket).on('any', function (eventType,incomingStream,data,callback) {
    var outgoingStream = ss.createStream();
    ss(consumerSocket).emit(eventType,outgoingStream,data,callback);
    incomingStream.pipe(outgoingStream);
  });

I'm posting this here so others can use it, maybe we can find a better solution in the future.

peteruithoven avatar Oct 10 '14 09:10 peteruithoven