OutStream.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * @file Simple wrapper for stream.Writable, used for sending binary data
  3. */
  4. 'use strict'
  5. var util = require('util'),
  6. stream = require('stream'),
  7. frame = require('./frame')
  8. /**
  9. * @class Represents the writable stream for binary frames
  10. * @param {Connection} connection
  11. * @param {number} minSize
  12. */
  13. function OutStream(connection, minSize) {
  14. var that = this
  15. this.connection = connection
  16. this.minSize = minSize
  17. this.buffer = Buffer.alloc(0)
  18. this.hasSent = false // Indicates if any frame has been sent yet
  19. stream.Writable.call(this)
  20. this.on('finish', function () {
  21. if (that.connection.readyState === that.connection.OPEN) {
  22. // Ignore if not connected anymore
  23. that.connection.socket.write(frame.createBinaryFrame(that.buffer, !that.connection.server, !that.hasSent, true))
  24. }
  25. that.connection.outStream = null
  26. })
  27. }
  28. module.exports = OutStream
  29. util.inherits(OutStream, stream.Writable)
  30. /**
  31. * @param {Buffer} chunk
  32. * @param {string} encoding
  33. * @param {Function} callback
  34. * @private
  35. */
  36. OutStream.prototype._write = function (chunk, encoding, callback) {
  37. var frameBuffer
  38. this.buffer = Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length)
  39. if (this.buffer.length >= this.minSize) {
  40. if (this.connection.readyState === this.connection.OPEN) {
  41. // Ignore if not connected anymore
  42. frameBuffer = frame.createBinaryFrame(this.buffer, !this.connection.server, !this.hasSent, false)
  43. this.connection.socket.write(frameBuffer, encoding, callback)
  44. }
  45. this.buffer = Buffer.alloc(0)
  46. this.hasSent = true
  47. if (this.connection.readyState !== this.connection.OPEN) {
  48. callback()
  49. }
  50. } else {
  51. callback()
  52. }
  53. }