Skip to content

Instantly share code, notes, and snippets.

@onionhammer
Created November 1, 2013 15:28
Show Gist options
  • Save onionhammer/7267136 to your computer and use it in GitHub Desktop.
Save onionhammer/7267136 to your computer and use it in GitHub Desktop.
Websocket read
proc read(ws: TWebSocketServer, client: TWebSocket): string =
var buffer = cstring(ws.buffer)
var read = client.socket.recv(buffer, 2)
var length = int(uint8(buffer[1]) and 127)
template readLength(size: int) =
## Read next `size` bytes to determine length
read = client.socket.recv(buffer, size, 0)
length = 0 #Reset the length to 0
let max = size * 8
for i in 1 .. size:
length += int(buffer[i - 1]) shl (max - (i * 8))
if length == 126: readLength(2)
elif length == 127: readLength(8)
#Read the rest of the data being transmitted
read = client.socket.recv(buffer, length + 4, 0)
result = newString(length)
#Decode the buffer & copy into result
var j = 0
for i in 0 .. length-1:
result[j] = char(uint8(buffer[i + 4]) xor uint8(buffer[j mod 4]))
inc(j)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment