2013-08-05 15:19:52 +00:00
|
|
|
(ns grub.websocket
|
2013-09-30 10:11:59 +00:00
|
|
|
(:require [grub.db :as db]
|
2013-08-05 15:19:52 +00:00
|
|
|
[org.httpkit.server :as httpkit]
|
2014-10-10 19:48:39 +00:00
|
|
|
[clojure.core.async :as a :refer [<! >! chan go]]
|
|
|
|
[cognitect.transit :as t])
|
|
|
|
(:import [java.io ByteArrayInputStream ByteArrayOutputStream]))
|
2013-08-05 15:19:52 +00:00
|
|
|
|
2014-08-19 20:24:19 +00:00
|
|
|
(defn disconnected [status ws-channel to from]
|
|
|
|
(println "Client disconnected:" (.toString ws-channel) "with status" status)
|
|
|
|
(a/close! to)
|
|
|
|
(a/close! from))
|
|
|
|
|
2014-10-10 19:48:39 +00:00
|
|
|
(defn write-msg [msg]
|
|
|
|
(let [out (ByteArrayOutputStream. 4096)
|
|
|
|
writer (t/writer out :json)]
|
|
|
|
(t/write writer msg)
|
|
|
|
(.toString out)))
|
|
|
|
|
|
|
|
(defn read-msg [msg]
|
|
|
|
(let [in (ByteArrayInputStream. (.getBytes msg))
|
2014-10-25 12:43:39 +00:00
|
|
|
reader (t/reader in :json)
|
|
|
|
received (t/read reader)]
|
|
|
|
received))
|
2014-10-10 19:48:39 +00:00
|
|
|
|
2014-10-25 19:15:32 +00:00
|
|
|
(defn add-connected-client! [ws-channel to from on-close]
|
2014-08-09 21:26:35 +00:00
|
|
|
(println "Client connected:" (.toString ws-channel))
|
2014-08-19 20:24:19 +00:00
|
|
|
(a/go-loop [] (if-let [event (<! to)]
|
2014-10-10 19:48:39 +00:00
|
|
|
(do (httpkit/send! ws-channel (write-msg event))
|
2014-08-19 20:24:19 +00:00
|
|
|
(recur))
|
|
|
|
(httpkit/close ws-channel)))
|
2014-10-10 19:48:39 +00:00
|
|
|
(httpkit/on-receive ws-channel #(a/put! from (read-msg %)))
|
2014-10-25 19:15:32 +00:00
|
|
|
(httpkit/on-close ws-channel (fn [status]
|
|
|
|
(println "Client disconnected:"
|
|
|
|
(.toString ws-channel)
|
|
|
|
"with status" status)
|
|
|
|
(on-close))))
|