tsblast.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var dgram = require('dgram'),
  2. util = require('util'),
  3. assert = require('assert');
  4. var async = require('async');
  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.on('finish', function() {
  23. this.client.close();
  24. });
  25. return this;
  26. }
  27. util.inherits(TsBlast, Writable);
  28. TsBlast.prototype._write = function(chunk, cb) {
  29. var self = this;
  30. if (chunk) {
  31. if (this.buffer.length)
  32. this.buffer = Buffer.concat([this.buffer, chunk]);
  33. else
  34. this.buffer = chunk;
  35. }
  36. var index = 0, psize = 188*7;
  37. function sendnext() {
  38. if ((self.buffer.length - index) >= psize) {
  39. self.client.send(self.buffer, index, psize, self.dst.port, self.dst.host, function(err, bytes) {
  40. index += psize;
  41. sendnext();
  42. });
  43. } else {
  44. /* if (!chunk) {
  45. self.client.send(self.buffer, index, self.buffer.length - index, self.dst.port, self.dst.host);
  46. index = self.buffer.length;
  47. }*/
  48. if (index) self.buffer = self.buffer.slice(index);
  49. cb();
  50. }
  51. }
  52. sendnext();
  53. };
  54. function tsblast(dst, options) {
  55. return new TsBlast(dst, options);
  56. }