嗨,我基本上使用 zmq 模块编写了一个客户端和一个服务器。我能够使用我的客户端向服务器发送一个普通字符串作为输入,并且数据显示良好。但是当我传递一个 JSON 对象时,它的打印方式不同。下面是我的客户代码
客户代码
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 对象。我卡在这里任何有关这方面的帮助都会很有帮助。