tsblast.js 1.5 KB

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