Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 6th, 2012  |  syntax: None  |  size: 1.86 KB  |  hits: 37  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // ZeroMQ PUB/SUB + Multicast (PGM) enabled event emitter for node.js
  2. // gleicon - 2011
  3.  
  4. var util = require("util");
  5. var events = require("events");
  6. var zeromq = require("zeromq"); // check the right path
  7. var sys = require("sys");
  8.  
  9. var address = "epgm://192.168.2.7:9999";
  10.  
  11. function DistEventEmitter(name, remote_node) {
  12.   events.EventEmitter.call(this);
  13.   this.id = new Date().getTime() + "-" + process.pid;
  14.   this.pub_socket = zeromq.createSocket('pub');
  15.   this.sub_socket = zeromq.createSocket('sub');
  16.        
  17.   this.pub_socket.connect(address, function(e){ if (e) console.log(e); });     
  18.   this.sub_socket.connect(address, function(e){ if (e) console.log(e); });
  19.        
  20.   this.sub_socket.subscribe("EVENTS");
  21.   this.sub_socket.on("message", DistEventEmitter.prototype._dispatch);
  22.  
  23. }
  24.  
  25. util.inherits(DistEventEmitter, events.EventEmitter);
  26.  
  27. DistEventEmitter.prototype._emit_local = DistEventEmitter.prototype.emit
  28.  
  29. DistEventEmitter.prototype._dispatch = function (data) {
  30.   DistEventEmitter.call(this);
  31.   try {
  32.     d = JSON.parse(data.toString('utf8').replace('EVENTS ', ''));
  33.     console.log('r: '+d.msg)
  34.     if (d.id != this.id) DistEventEmitter.prototype._emit_local(d.event_name, d.msg);                  
  35.         console.log('rec: '+d.msg);
  36.     } catch (e) { console.log(e); }    
  37. }
  38.  
  39. DistEventEmitter.prototype._broadcast = function(w) {
  40.   DistEventEmitter.call(this);
  41.   pkt = JSON.stringify({ "id": this.id,
  42.                          "event_emitter": "data_ws",
  43.                          "event_name" : "data",
  44.                          "msg": w });
  45.  
  46.   this.pub_socket.send("EVENTS " + pkt);
  47. }
  48.  
  49. DistEventEmitter.prototype.emit = function(evt, data) {
  50.   this._broadcast(data)
  51.   return this._emit_local(evt, data);
  52. }
  53.  
  54. // test
  55. var de = new DistEventEmitter();
  56. de.on("data", function(data) { console.log('Received data: "' + data + '"'); })
  57. de.on("error", function(data) { console.log('Received data (Error): "' + data + '"'); })
  58.  
  59. de.emit("data", "It works!")
  60. de.emit("data", "It works 2")