Guest User

Untitled

a guest
Jan 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. hexToBuffer = (hex, padding) ->
  2. n = lpad hex.toString(16), '0', padding
  3. list = []
  4.  
  5. while n.length > 0
  6. head = n.substr 0, n.length - 2
  7. tail = n.substr n.length - 2
  8.  
  9. list.unshift parseInt tail, 16
  10.  
  11. n = head
  12.  
  13. new Buffer list
  14.  
  15. lpad = (str, padString, length) ->
  16. str = padString + str while str.length < length
  17. str
  18.  
  19. generateMask = (length = 8) ->
  20. buffer = new Buffer length
  21. max = Math.pow(16, length) - 1
  22.  
  23. for i in [0..length]
  24. buffer[i] = Math.floor( Math.random() * max )
  25.  
  26. buffer
  27.  
  28. generateFrame = (isFinal, kind, mask = null, length) ->
  29. firstByte = 0
  30. secondByte = 0
  31.  
  32. firstTwoBytes = null
  33. lengthBytes = null
  34. maskBytes = null
  35.  
  36. if isFinal
  37. firstByte += 0x80
  38.  
  39. if kind == 'continuation'
  40. firstByte += 0x00
  41. else if kind == 'text'
  42. firstByte += 0x01
  43. else if kind == 'binary'
  44. firstByte += 0x02
  45.  
  46. if mask
  47. secondByte += 0x80
  48.  
  49. if mask
  50. maskBytes = mask
  51. else
  52. maskBytes = new Buffer []
  53.  
  54. if length < 127
  55. initialLength = length
  56. lengthBytes = new Buffer []
  57.  
  58. secondByte += initialLength
  59. else if length < 0xffff
  60. initialLength = 126
  61. lengthBytes = hexToBuffer length, 4
  62.  
  63. secondByte += initialLength
  64. else if length <= 0xffffffffffffffff
  65. initialLength = 127
  66. lengthBytes = hexToBuffer length, 10
  67.  
  68. secondByte += initialLength
  69. else
  70. throw new Error 'Length is too large.'
  71.  
  72. firstTwoBytes = new Buffer 2
  73. firstTwoBytes[0] = firstByte
  74. firstTwoBytes[1] = secondByte
  75.  
  76. frame = new Buffer(firstTwoBytes.length + lengthBytes.length + maskBytes.length)
  77.  
  78. firstTwoBytes.copy frame
  79. lengthBytes.copy frame, firstTwoBytes.length
  80. maskBytes.copy frame, (firstTwoBytes.length + lengthBytes.length)
  81.  
  82. frame
  83.  
  84. console.log 'one', generateFrame true, 'text', null, 120
  85. console.log 'two', generateFrame true, 'text', generateMask(), 120
Add Comment
Please, Sign In to add comment