Skip to content

Instantly share code, notes, and snippets.

@3rd-Eden
Created March 30, 2011 11:04
Show Gist options
  • Save 3rd-Eden/894207 to your computer and use it in GitHub Desktop.
Save 3rd-Eden/894207 to your computer and use it in GitHub Desktop.
module.exports = function(constructor){
var io = constructor.Listener.prototype;
/**
* Publishes messages over variouse of channels
*
* @param {Socket.IO.Client} current The client that sends the message
* @param {Array} rooms The rooms that receive the message
* @param {Mixed} message The message for the channel
* @returns {Socket.IO.Listener}
* @api public
*/
io.publish = function(current, rooms, message){
var keys = Object.keys( this.clients )
, i = keys.length
, client;
while( i-- ){
// reduce lookups
client = this.clients[ keys[i] ];
if( client === current ) continue;
if (client && client.rooms && client.rooms.some(function(room){
return rooms.indexOf(room) !== -1
}))
{
client.send(message);
}
}
return this;
};
};
@3rd-Eden
Copy link
Author

And you can call the module:

var io = require('socket.io'); require("./extend.io")(io);

Then

var socket = io.listen(app);

and you can broadcast to a subset of channels:

socket.publish(client, ['name','of','rooms'], "Hello users in my rooms")

complete example implementation:

var socket = io.listen(app);
socket.on("connection", function(client){
    client.rooms = ["rooms","users","pewpew"];
    socket.publish(client, client.rooms, "hello my fellow connected users");
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment