node.js使用zmq通信
  TEZNKK3IfmPf 2023年11月12日 25 0

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');
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月12日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年04月19日   19   0   0 client调用server
  TEZNKK3IfmPf   2023年11月13日   39   0   0 sqlserver
TEZNKK3IfmPf