During my quest to learn Clojure I am currently facing problems with setting up websocket communitation. After many different approaches, I ended up using aleph.
What I managed to achieve:
What I lack is means to trigger a handler function whenever one of the connected clients sends something via the websocket.
My code so far:
(ns wonders7.core.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]
[aleph.http :as http]
[manifold.stream :as stream]
[clojure.tools.logging :refer [info]]))
(defn uuid [] (str (java.util.UUID/randomUUID)))
(def clients (atom {}))
(defn ws-create-handler [req]
(let [ws @(http/websocket-connection req)]
(info "ws-create-handler")
(stream/on-closed ws #(swap! clients dissoc ws))
(swap! clients assoc ws (uuid))))
(defroutes app-routes
(GET "/ws" [] ws-create-handler)
(route/not-found "Not Found"))
(def app
(wrap-defaults app-routes site-defaults))
(defn msg-to-client [[client-stream uuid]]
(stream/put! client-stream "The server side says hello!"))
(defn msg-broadcast []
(map #(msg-to-client %) @clients))
;(stream/take! (first (first @clients)))
;(http/start-server app {:port 8080})
I start the Netty server with the commented out http/start-server aleph call. I also managed to fetch messages from the client via manual stream/take! call (also commented out). What I need to figure out is how to trigger this taking automatically when something comes in.
Thanks in advance for any help!
The function you're looking for is (manifold.stream/consume callback stream)
, which will invoke the callback for each message that comes off the stream.