Skip to content

Instantly share code, notes, and snippets.

@viperscape
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viperscape/8918565 to your computer and use it in GitHub Desktop.
Save viperscape/8918565 to your computer and use it in GitHub Desktop.
(defn get-chunk [conn buf]
"returns map of bytes and size of buffer for data recieved in stream (buffered input stream);
buf would be something like: (make-array Byte/TYPE 4096)"
(let [bufsize (.read conn buf)] ;;blocking
{:size bufsize :data buf}))
(defn- ws-decode [frame]
"decodes websocket frame"
(let [data (:data frame)
dlen (bit-and (second data) 127)
mstart (if (== dlen 127) 10 (if (== dlen 126) 4 2))
mask (drop mstart (take (+ mstart 4) data))
msg (make-array Byte/TYPE (- (:size frame) (+ mstart 4)))]
(loop [i (+ mstart 4), j 0]
(aset-byte msg j (byte (bit-xor (nth data i) (nth mask (mod j 4)))))
(if (< i (dec(:size frame))) (recur (inc i) (inc j))))
msg))
(defn- ws-encode [data]
"takes in bytes, return websocket frame (no chunking available); todo:chunk"
(let [len (count data)
blen (if (> len 65535) 10 (if (> len 125) 4 2))
buf (make-array Byte/TYPE (+ len blen))
_ (aset-byte buf 0 -127) ;;(bit-or (unchecked-byte 0x80) (unchecked-byte 0x1)
_ (if (= 2 blen)
(aset-byte buf 1 len) ;;mask 0, len
(do
(dorun(map #(aset-byte buf %1 (unchecked-byte (bit-and (bit-shift-right len (*(- %2 2) 8)) 255))) (range 2 blen) (into ()(range 2 blen))))
(aset-byte buf 1 (if (> blen 4) 127 126))))
_ (System/arraycopy data 0 buf blen len)]
buf))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment