Nodejs在pub / sub中从客户端发布

时间:2012-10-23 10:39:56

标签: javascript node.js redis socket.io

我正在尝试在nodejs中构建一个小应用程序来发布和订阅。我被困在如何从客户端发布。这是我的代码。

这是我的服务器代码(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);
  });
});

这是客户端代码

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);
  }
}

1 个答案:

答案 0 :(得分:4)

您可以在客户端和服务器websocket连接上使用emit方法,取自Socket.io

var socket = io.connect(narad.url);
socket.emit('publish', 'message');

然后在您的服务器上收听消息:

socket.on('publish', function (data) {
  // Emit the published message to the subscribers
  socket.emit('subscribers', data);
  console.log(data);
});

这样您就可以使用websockets的双向通信,而无需使用某些POST api。