Close up client channels properly on disconnect

This commit is contained in:
Nicholas Kariniemi 2014-10-25 22:15:32 +03:00
parent 4883013470
commit 412bf29f57
2 changed files with 13 additions and 4 deletions

View file

@ -62,9 +62,14 @@
(httpkit/with-channel request ws-channel
(let [to-client (chan)
from-client (chan)
new-states (chan (a/sliding-buffer 1))]
new-states (chan (a/sliding-buffer 1))
on-close (fn []
(a/unsub new-states-pub :new-state new-states)
(a/close! new-states)
(a/close! from-client)
(a/close! to-client))]
(a/sub new-states-pub :new-state new-states)
(ws/add-connected-client! ws-channel to-client from-client)
(ws/add-connected-client! ws-channel to-client from-client on-close)
(sync/make-server-agent to-client from-client new-states states)))
(handler request))))

View file

@ -22,11 +22,15 @@
received (t/read reader)]
received))
(defn add-connected-client! [ws-channel to from]
(defn add-connected-client! [ws-channel to from on-close]
(println "Client connected:" (.toString ws-channel))
(a/go-loop [] (if-let [event (<! to)]
(do (httpkit/send! ws-channel (write-msg event))
(recur))
(httpkit/close ws-channel)))
(httpkit/on-receive ws-channel #(a/put! from (read-msg %)))
(httpkit/on-close ws-channel #(disconnected % ws-channel to from)))
(httpkit/on-close ws-channel (fn [status]
(println "Client disconnected:"
(.toString ws-channel)
"with status" status)
(on-close))))