tsblast.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.client.bind();
  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, encoding, 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. }