pubsub.js
A lightweight publish/subscribe server & client written in javascript.
The publish/subscribe model is perfect for making your web application appear real-time. Imagine several people all looking at the same page, when someone makes a change to the page it's instantly reflected to all other viewers of that page. This is pubsub.js
!
A Channel
is a group of subscribers all listening for publish, join, & leave events. Channels are created when needed and are destroyed when there are no subscribers.
A Client
is a connection to the server from a web application that can be subscribed to any number of Channels.
pubsub.js
is built with safety in mind. All data sent to the server is validated before it creates channels, subscribes clients, or publishes to a channel.
Installing the Client
The easiest way to install pubsub.js is through bower via bower install clickermonkey-pubsubjs
Installing the Server
npm install clickermonkey-pubsubjs
Running the Server
node node_modules/clickermonkey-pubsubjs/pubsub-server.js path/to/my/config.js
Client Code
var pubsub = new PubSub('http://localhost:3000');
var channel = pubsub.subscribe('channel ID', 'user token');
channel.onpublish = function(data) {
console.log('data received:', data);
};
channel.onjoin = function(userToken) {
console.log('user join:', userToken);
};
channel.onleave = function(userToken) {
console.log('user leave:', userToken);
};
channel.publish('Hello World!');
channel.unsubscribe();
(see examples/chat.html for a chat demo)
Configuration (config.js)
{
port: 3000,
echoPublish: false,
sendJoinLeaveEvents: true,
maxChannels: -1,
maxClients: -1,
ignoreInvalidClients: true,
sendLastPublishesOnJoin: 10,
sendExistingClientsOnJoin: true,
requireSubscription: true,
debug: function()
{
console.log.apply( console, arguments );
},
validIds:
{
'number': true,
'string': true,
'boolean': true,
'object': false,
'undefined': false
},
validateId: function(id)
{
var promise = new Promise( this );
if ( this.validIds[ typeof id ] )
{
promise.$success();
}
else
{
promise.$failure();
}
return promise;
},
validTokens:
{
'number': true,
'string': true,
'boolean': true,
'undefined': true,
'object': false
},
validateToken: function(token)
{
var promise = new Promise( this );
if ( this.validTokens[ typeof token ] )
{
promise.$success();
}
else
{
promise.$failure();
}
return promise;
},
validPublish:
{
'number': true,
'string': true,
'boolean': true,
'undefined': true,
'object': true
},
validatePublish: function(message, client, channel)
{
var promise = new Promise( this );
if ( this.validPublish[ typeof message ] )
{
promise.$success();
}
else
{
promise.$failure();
}
return promise;
}
}