wechat wss demo

generate.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict'
  2. var Buffer = require('safe-buffer').Buffer
  3. var writeToStream = require('./writeToStream')
  4. var EE = require('events').EventEmitter
  5. var inherits = require('inherits')
  6. function generate (packet) {
  7. var stream = new Accumulator()
  8. writeToStream(packet, stream)
  9. return stream.concat()
  10. }
  11. function Accumulator () {
  12. this._array = new Array(20)
  13. this._i = 0
  14. }
  15. inherits(Accumulator, EE)
  16. Accumulator.prototype.write = function (chunk) {
  17. this._array[this._i++] = chunk
  18. return true
  19. }
  20. Accumulator.prototype.concat = function () {
  21. var length = 0
  22. var lengths = new Array(this._array.length)
  23. var list = this._array
  24. var pos = 0
  25. var i
  26. var result
  27. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  28. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  29. else lengths[i] = Buffer.byteLength(list[i])
  30. length += lengths[i]
  31. }
  32. result = Buffer.allocUnsafe(length)
  33. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  34. if (typeof list[i] !== 'string') {
  35. list[i].copy(result, pos)
  36. pos += lengths[i]
  37. } else {
  38. result.write(list[i], pos)
  39. pos += lengths[i]
  40. }
  41. }
  42. return result
  43. }
  44. module.exports = generate