pub.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Module dependencies.
  3. */
  4. var Socket = require('./sock');
  5. var slice = require('../utils').slice;
  6. /**
  7. * Expose `PubSocket`.
  8. */
  9. module.exports = PubSocket;
  10. /**
  11. * Initialize a new `PubSocket`.
  12. *
  13. * @api private
  14. */
  15. function PubSocket() {
  16. Socket.call(this);
  17. }
  18. /**
  19. * Inherits from `Socket.prototype`.
  20. */
  21. PubSocket.prototype.__proto__ = Socket.prototype;
  22. /**
  23. * Send `msg` to all established peers.
  24. *
  25. * @param {Mixed} msg
  26. * @api public
  27. */
  28. PubSocket.prototype.send = function(msg){
  29. var socks = this.socks;
  30. var len = socks.length;
  31. var buf = this.pack(arguments);
  32. for (var sock of socks) {
  33. if (sock.writable) sock.write(buf);
  34. }
  35. return this;
  36. };
  37. PubSocket.prototype.sendv2 = function(data, cb){
  38. var socks = this.socks;
  39. var len = socks.length;
  40. var sock;
  41. if (len == 0)
  42. return process.nextTick(cb);
  43. var buf = this.pack([data]);
  44. var i = 0;
  45. socks.forEach(function(sock) {
  46. if (sock.writable)
  47. sock.write(buf, function() {
  48. i++;
  49. if (i == len)
  50. process.nextTick(cb);
  51. });
  52. else {
  53. i++;
  54. if (i == len)
  55. process.nextTick(cb);
  56. }
  57. });
  58. return this;
  59. };