How can I send and receive WebSocket messages on the server side?

后端 未结 11 2165
轻奢々
轻奢々 2020-11-22 06:21
  • How can I send and receive messages on the server side using WebSocket, as per the protocol?

  • Why do I get seemingly random bytes at the server when

11条回答
  •  天命终不由人
    2020-11-22 06:49

    Clojure, the decode function assumes frame is sent as map of {:data byte-array-buffer :size int-size-of-buffer}, because the actual size may not be the same size as the byte-array depending on chunk size of your inputstream.

    Code posted here: https://gist.github.com/viperscape/8918565

    (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 2 (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"
      (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))
    

提交回复
热议问题