Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(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
You can’t perform that action at this time.