How to customize socket.io's connection event by room?

1.1k views Asked by At

When a socket connects to a socket.io server, a connection event is triggered. The function that handles such event can be overrided to add custom behavior to the connection.

I want to add a function to handle the connection event, but for a socket.io room.

I was trying something like (with socket.io 0.9.14):

io.sockets.in('someNamespace/someRoom').on('connection', function () {
    //custom actions here
}

But it doesn't seem to work. The behavior is attached to the default connection event and triggered on every connection.

Is it possible to achieve what I'm trying? any suggestions?

Thanks in advance.

2

There are 2 answers

2
M Omayr On

If I've understood your question clearly, you're trying to use namespaces. Then you should do it like this:

io.of('/someNamespace/someRoom').on('connection', function (socket) {
  //your actions here
});
0
jpgc On

It is possible to simulate a similar behavior (similar to the on-connection handler) for rooms, using the callback (or fn) argument for the socket.io 0.9.14 join function, like this:

socket.join('some/room', function handleJoin () {
    //do something when socket joins to 'some/room'
})

For the version 0.9.14 of socket.io, when the join function has a second argument, a warning is displayed telling:

Client#join callback is deprecated

But for the current one, in the master branch (version 1.0.0-pre), the warning is no longer there and the callback function can be used for error handling on room joining. So, it might be safe to rely on the existence of this argument in the future.

Finally, by using a wrapper function on the join call, it is possible to preserve the closure for the call, thus providing the same arguments that an on connection handler normally takes.

e.g. (in some place inside the server)

var someVar = 'some value';
socket.join('some/room', function () {
    handleJoin(someVar);
});

And then, somevar will be available inside the handleJoin function (somevar could be the room name, for example). Of course, it is a very simple example and it could be adapted to meet different requirements or to comply with the upcoming version of the join function.

Hope this helps.