Skip to content

Forwarding communication #1715

Closed
Closed
@peteruithoven

Description

@peteruithoven

I'd like to forward websocket communication (custom events, messages etc). I have to forward communication between clients because they can't reach each other directly (because they are usually behind routers etc).
Is there any way to handle any event, so I don't have to specify all the event names on my server?

I would really like to do is the following:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen(3000);

var subject = null;

var nsp = io.of("/");
nsp.on('connection', function(socket){
  if(socket.handshake.query.isSubject) {
    subject = socket;
    // forward all events from subject to other clients in namespace
    subject.on("anything",function(data) {
      subject.broadcast.emit(data.type,data.payload);
    });
  } else {
    // forward all events from clients to subject
    socket.on("anything",function(data) {
      subject.emit(data.type,data.payload);
    }); 
  }
});

Looking through the code I found the onevent handler, and inspired by #1185 I figured out the following solution. My question is, is there a better solution?
(If there isn't I hope the solution is useful more people)

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen(3000);

var subject = null;

var nsp = io.of("/");
nsp.on('connection', function(socket){
  if(socket.handshake.query.isSubject) {
    subject = socket;
  }

  var oneventHandler = socket.onevent;
  socket.onevent = function() {
    oneventHandler.apply(this,arguments);
    var packet = arguments[0];
    var eventType = packet.data[0];
    var eventData = packet.data[1];
    var eventCallback = packet.data[2];
    if(socket === subject) {
      // forward all events from subject to other clients in namespace
      subject.broadcast.emit(eventType,eventData);
    } else {
      // forward all events from clients to subject
      subject.emit(eventType,eventData);
    }
  };
});

This handles all events, to go even more generic you could override onpacket.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions