天天看点

在node中实现zeromq的订阅发布模式

  1. 安装zeromq
    cnpm install [email protected]
               
  2. server端代码:
    // pubber.js
    var zmq = require("zeromq"),
      sock = zmq.socket("pub");
     
    sock.bindSync("tcp://127.0.0.1:3000");
    console.log("Publisher bound to port 3000");
     
    setInterval(function() {
      console.log("sending a multipart message envelope");
      sock.send(["kitty cats", "one!"]);
      sock.send(["hello", "world"]);
    }, 1000);
               
  3. 客户端代码:
    // subber.js
    var zmq = require("zeromq"),
      sock = zmq.socket("sub");
     
    sock.connect("tcp://193.112.215.17:7003");
    //指定订阅的topic
    sock.subscribe("hello");
    console.log("Subscriber connected to port 3000");
    
    
    sock.on("message", function(topic, message) {
    	console.log(topic);
    	console.log(message);
      //arr.forEach(function(v,index,a){
    		//每一个数组中的值
            //console.log(v);
    		//每一个值的索引
            //console.log(index);
    		//数组本身
            //console.log(a[1]);
    		//for(var i=0;i<a.length;i++){
    		//	console.log(a[i]);
    		//}
    	//});
    	
    });