Skip to content

Instantly share code, notes, and snippets.

@rjungemann
Created September 12, 2011 02:30
Show Gist options
  • Save rjungemann/1210469 to your computer and use it in GitHub Desktop.
Save rjungemann/1210469 to your computer and use it in GitHub Desktop.
Generate WebSocket frames in CoffeeScript
hexToBuffer = (hex, padding) ->
n = lpad hex.toString(16), '0', padding
list = []
while n.length > 0
head = n.substr 0, n.length - 2
tail = n.substr n.length - 2
list.unshift parseInt tail, 16
n = head
new Buffer list
lpad = (str, padString, length) ->
str = padString + str while str.length < length
str
generateMask = (length = 8) ->
buffer = new Buffer length
max = Math.pow(16, length) - 1
for i in [0..length]
buffer[i] = Math.floor( Math.random() * max )
buffer
generateFrame = (isFinal, kind, mask = null, length) ->
firstByte = 0
secondByte = 0
firstTwoBytes = null
lengthBytes = null
maskBytes = null
if isFinal
firstByte += 0x80
if kind == 'continuation'
firstByte += 0x00
else if kind == 'text'
firstByte += 0x01
else if kind == 'binary'
firstByte += 0x02
if mask
secondByte += 0x80
if mask
maskBytes = mask
else
maskBytes = new Buffer []
if length < 127
initialLength = length
lengthBytes = new Buffer []
secondByte += initialLength
else if length < 0xffff
initialLength = 126
lengthBytes = hexToBuffer length, 4
secondByte += initialLength
else if length <= 0xffffffffffffffff
initialLength = 127
lengthBytes = hexToBuffer length, 10
secondByte += initialLength
else
throw new Error 'Length is too large.'
firstTwoBytes = new Buffer 2
firstTwoBytes[0] = firstByte
firstTwoBytes[1] = secondByte
frame = new Buffer(firstTwoBytes.length + lengthBytes.length + maskBytes.length)
firstTwoBytes.copy frame
lengthBytes.copy frame, firstTwoBytes.length
maskBytes.copy frame, (firstTwoBytes.length + lengthBytes.length)
frame
console.log 'one', generateFrame true, 'text', null, 120
console.log 'two', generateFrame true, 'text', generateMask(), 120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment