node.js使用zmq通信

server端


var zmq = require("zmq");  
var socket = zmq.socket("req");  
var counter = 0;
// Just a helper function for logging to the console with a timestamp.
function logToConsole (message) {  
  console.log("[" + new Date().toLocaleTimeString() + "] " + message);
}
function sendMessage (message) {  
  logToConsole("Sending: " + message);
  socket.send(message);
}
// Add a callback for the event that is invoked when we receive a message.
socket.on("message", function (message) {  
  // Convert the message into a string and log to the console.
  logToConsole("Response: " + message.toString("utf8"));
});
// Begin listening for connections on all IP addresses on port 9998.
socket.bind("tcp://*:9998", function (error) {  
  if (error) {
    logToConsole("Failed to bind socket: " + error.message);
    process.exit(0);
  }
  else {
    logToConsole("Server listening on port 9998");
    // Increment the counter and send the value to the clients every second.
    setInterval(function () { sendMessage(counter++); }, 1000);
  }
});


client端


var zmq = require("zmq");  
var socket = zmq.socket("rep");
// Just a helper function for logging to the console with a timestamp.
function logToConsole (message) {  
  console.log("[" + new Date().toLocaleTimeString() + "] " + message);
}
// Add a callback for the event that is invoked when we receive a message.
socket.on("message", function (message) {  
  // Convert the message into a string and log to the console.
  logToConsole("Received message: " + message.toString("utf8"));
  // Send the message back aa a reply to the server.
  socket.send(message);
});
// Connect to the server instance.
socket.connect('tcp://127.0.0.1:9998');  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟世者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值