tsblast.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var dgram = require('dgram'),
  2. util = require('util'),
  3. assert = require('assert');
  4. var async = require('async'),
  5. Writable = require('readable-stream/writable');
  6. module.exports = tsblast;
  7. exports.TsBlast = TsBlast;
  8. function TsBlast(dst, options) {
  9. var self = this;
  10. Writable.call(this, options);
  11. if (typeof dst === 'number')
  12. dst = {port:dst, host:'localhost'};
  13. this.dst = dst;
  14. this.options = options || {};
  15. this.buffer = new Buffer(0);
  16. this.client = dgram.createSocket('udp4');
  17. this.on('finish', function() {
  18. this.client.close();
  19. });
  20. return this;
  21. }
  22. util.inherits(TsBlast, Writable);
  23. TsBlast.prototype._write = function(chunk, cb) {
  24. var self = this;
  25. if (chunk) {
  26. if (this.buffer.length)
  27. this.buffer = Buffer.concat([this.buffer, chunk]);
  28. else
  29. this.buffer = chunk;
  30. }
  31. var index = 0, psize = 188*7;
  32. function sendnext() {
  33. if ((self.buffer.length - index) >= psize) {
  34. self.client.send(self.buffer, index, psize, self.dst.port, self.dst.host, function(err, bytes) {
  35. index += psize;
  36. sendnext();
  37. });
  38. } else {
  39. /* if (!chunk) {
  40. self.client.send(self.buffer, index, self.buffer.length - index, self.dst.port, self.dst.host);
  41. index = self.buffer.length;
  42. }*/
  43. if (index) self.buffer = self.buffer.slice(index);
  44. cb();
  45. }
  46. }
  47. sendnext();
  48. };
  49. function tsblast(dst, options) {
  50. return new TsBlast(dst, options);
  51. }