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

我正在尝试在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);
  }
}

您可以在Socket.io中的客户端和服务器websocket连接上使用emit方法:

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。

链接地址: http://www.djcxy.com/p/64965.html

上一篇: Nodejs Publish from Client in pub/sub

下一篇: Windows Event implementation in Linux using conditional variables?