tsblast.js 1.5 KB

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