diff --git a/src/clj/grub/websocket.clj b/src/clj/grub/websocket.clj index 6158fe4..38acd35 100644 --- a/src/clj/grub/websocket.clj +++ b/src/clj/grub/websocket.clj @@ -5,7 +5,7 @@ (def incoming-events (chan)) -(def connected-clients (atom [])) +(def connected-clients (atom {})) (def ws-channel-id-count (atom 0)) @@ -15,11 +15,18 @@ (defn add-connected-client! [ws-channel] (let [ws-channel-id (get-unique-ws-id) client-chan (chan)] - (swap! connected-clients - conj - {:id ws-channel-id :channel client-chan}) + (swap! connected-clients #(assoc % ws-channel-id client-chan)) [ws-channel-id client-chan])) +(defn remove-connected-client! [status ws-channel ws-channel-id client-chan] + (println "Client disconnected:" + (.toString ws-channel) + (str "(" ws-channel-id ")") + "with status" status) + (swap! connected-clients #(dissoc % ws-channel-id)) + (println (count @connected-clients) "client(s) still connected") + (a/close! client-chan)) + (defn add-event-to-incoming-channel [raw-event ws-channel-id] (let [parsed-event (read-string raw-event) @@ -27,16 +34,12 @@ (println "Received event" event) (go (>! incoming-events event)))) -(defn forward-client-events-to-others [ws-channel ws-channel-id] - (httpkit/on-receive ws-channel - #(add-event-to-incoming-channel % ws-channel-id))) - (defn forward-other-events-to-client [c ws-channel] - (a/go-loop [] (let [event ( @connected-clients + (dissoc my-ws-channel-id) + (vals))) (defn push-event-to-others [orig-event] (let [my-ws-channel-id (:ws-channel orig-event) event (dissoc orig-event :ws-channel)] - (go (doseq [{ch :channel} (get-other-clients my-ws-channel-id)] - (>! ch event))))) + (go (doseq [c (get-other-client-channels my-ws-channel-id)] + (>! c event))))) (defn pass-received-events-to-clients-and-db [db-chan] (let [in' (a/mult incoming-events)