Nodejs Publish from Client in pub/sub
I am trying to build a small app in nodejs to publish and subscribe. I am stucked in how I can publish from client side. Here is the code I have.
Here is my server code (server.js)
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app);
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.post('/publish/:channel/:event/', function(req, res) {
console.log("**************************************");
var params = req.params;
console.log(req.params);
console.log(req.body);
var data = req.body;
console.log("**************************************");
var result = io.sockets.emit(params.channel,{event:params.event,data:data});
//console.log(result);
console.log("**************************************");
res.sendfile(__dirname + '/public/index.html');
});
//include static files
app.use(express.static(__dirname + '/public'));
server = server.listen(3000);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (s) {
socket = s
socket.emit('c1', { hello: 'world' });
socket.on('test', function (data) {
socket.emit('c1', { hello: 'world' });
console.log('test');console.log(data);
});
});
And here is client code
var narad = {};
narad.url = 'http://192.168.0.46:3000';
narad.lisentingChannels = {}
var socket = io.connect(narad.url);
function Channel(channelName) {
this.channelName = channelName; //serviceObject is the object of
this.events = {};
};
Channel.prototype.bind = function (event, callback) {
this.events[event] = callback;
};
narad.subscribe = function (channelName) {
var channel = new Channel(channelName)
this.lisentingChannels[channelName] = channel;
socket.on(channelName, this.callbackBuilder(channel))
return this.lisentingChannels[channelName];
}
narad.callbackBuilder = function (channel) {
return function (data) {
var callback = channel.events[data["event"]];
callback(data.data);
}
}
You can use the emit
method on both the client and the server websocket connections, taken from Socket.io:
var socket = io.connect(narad.url);
socket.emit('publish', 'message');
Then on your server you listen for the message:
socket.on('publish', function (data) {
// Emit the published message to the subscribers
socket.emit('subscribers', data);
console.log(data);
});
This way you are using the bi-directional communication of websockets without having to use some POST
api.