Skip to content

Instantly share code, notes, and snippets.

@den1k
Created June 9, 2021 15:38
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 den1k/74052f28a08d099c463d7a3a124c18f8 to your computer and use it in GitHub Desktop.
Save den1k/74052f28a08d099c463d7a3a124c18f8 to your computer and use it in GitHub Desktop.
CLJ(S) Local Websocket Benchmark
(defn ws-latency-conn
[url
{:keys [on-open on-close on-message binary-type]
:or {binary-type :arraybuffer}}]
(let [socket (js/WebSocket. url)]
(set! (.-binaryType socket) (name binary-type))
(set! (.-onopen socket)
(or on-open
#(js/console.log "WebSocket opened:" url %)))
(set! (.-onmessage socket)
(fn [e]
(on-message (.-data e))))
(set! (.-onclose socket)
(or on-close
#(js/console.log "WebSocket closed:" url %)))
socket))
(def times (atom []))
(def latency-socket
(ws-latency-conn
"ws://localhost:4500/latency-benchmark-ws"
{:on-message #(do (swap! times conj (- (js/performance.now) %))
;; 10000 requests
(when (< (count @times) 10000)
(.send latency-socket (js/performance.now))))
;; start benchmark
:on-open #(.send latency-socket (js/performance.now))}))
(comment
(count @times)
; => 10000
;; compute average
(/ (apply + @times) (count @times))
; => 0.23315749996108934
)
(require '[org.httpkit.server :as httpkit])
(defonce latency-ws-chan (atom nil))
(defn latency-ws-handler [req]
(httpkit/as-channel
req
{:on-open (fn [ch]
(println :opened ch)
(reset! latency-ws-chan ch))
:on-receive (fn [ch msg]
(let []
(println :msg msg)
(httpkit/send! ch msg)
))
:on-ping (fn [ch data]
(println :ping data))
:on-close (fn [ch status]
(println :closed status)
(reset! latency-ws-chan nil))}))
(def ws-server
(httpkit/run-server
latency-ws-handler
{:port 4500
:legacy-return-value? false}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment