将json对象传递给zmq服务器

时间:2013-10-15 13:42:20

标签: node.js zeromq

您好我基本上使用zmq模块编写了一个客户端和一个服务器。我能够使用我的客户端将正常的字符串作为输入发送到服务器并且数据显示良好。但是当我传递一个JSON对象时,它正在获取打印不同.Below是我的客户代码

  

客户代码

var zmq = require('zmq');
// socket to talk to server
console.log("Connecting to hello world server...");
var requester = zmq.socket('req');

var x = 0;
requester.on("message", function(reply) {

console.log("Received reply for client from server", ": [", reply.toString(), ']');
x += 1;
if (x === 5) {
requester.close();
 process.exit(0);

} });

requester.connect("tcp://localhost:7000");

for (var i = 0; i < 5; i++) {

console.log("Sending request", i, '...');
requester.send({"AdvisorId" : "71864", "Phone": "952-921-4972"});
}

process.on('SIGINT', function() {
requester.close();
});
  

服务器代码

// Hello World server
// Binds REP socket to tcp://*:7000
// Expects "Hello" from client, replies with "world"

var zmq = require('zmq');

// socket to talk to clients
var responder = zmq.socket('rep');

responder.on('message', function(request) {

 console.log("Received request: [", request, "]");
console.log(typeof request)

 // do some 'work'
 setTimeout(function() {

// send reply back to client.
responder.send("world");
 }, 1000);
});

responder.bind('tcp://*:7000', function(err) {
if (err) {
console.log(err);
 } else {

console.log("Listening on 7000...");
 }
});

process.on('SIGINT', function() {
responder.close();
});
  

在服务器中请求数据

Received request: [ <SlowBuffer 5b 6f 62 6a 65 63 74 20 4f 62 6a 65 63 74 5d> ]

而我发送的数据是{“AdvisorId”:“71864”,“Phone”:“952-921-4972”}这是一个JSON对象。我在这里遇到任何有关这方面的帮助都会非常有帮助。

2 个答案:

答案 0 :(得分:3)

var jsonObject={"AdvisorId" : "71864", "Phone": "952-921-4972"} ;
var stringObject=JSON.stringify(jsonObject);
requester.send(stringObject);

这将有效.. !!

答案 1 :(得分:0)

ZeroMq支持string和byte []数据,而不支持对象。

试试这个:

requester.send("{AdvisorId" : "71864", "Phone": "952-921-4972}");