简体   繁体   English

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

[英]Nodejs Publish from Client in pub/sub

I am trying to build a small app in nodejs to publish and subscribe. 我正在尝试在nodejs中构建一个小应用程序来发布和订阅。 I am stucked in how I can publish from client side. 我被困在如何从客户端发布。 Here is the code I have. 这是我的代码。

Here is my server code (server.js) 这是我的服务器代码(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 : 您可以在客户端和服务器websocket连接上使用emit方法,取自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. 这样您就可以使用websockets的双向通信,而无需使用某些POST API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM