tsblast.js 1.5 KB

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