Skip to main content

as-channel

function

org.httpkit.server/as-channel

(as-channel [ring-req {:keys [on-receive on-ping on-close on-open init on-handshake-error], :or {on-handshake-error (fn [ch] (send! ch bad-ring-websocket-resp true))}}])
Returns `{:body ch}`, where `ch` is the request's underlying asynchronous HTTP or WebSocket `AsyncChannel`. Main options: :init - (fn [ch]) for misc pre-handshake setup. :on-receive - (fn [ch message]) called for client WebSocket messages. :on-ping - (fn [ch data]) called for client WebSocket pings. :on-close - (fn [ch status-code]) called when AsyncChannel is closed. :on-open - (fn [ch]) called when AsyncChannel is ready for `send!`, etc. See `Channel` protocol for more info on handlers and `AsyncChannel`s. See `org.httpkit.timer` ns for optional timeout utils. --- Example - Async HTTP response: (def clients_ (atom #{})) (defn my-async-handler [ring-req] (as-channel ring-req {:on-open (fn [ch] (swap! clients_ conj ch))})) ;; Somewhere else in your code (doseq [ch @clients_] (swap! clients_ disj ch) (send! ch {:status 200 :headers {"Content-Type" "text/html"} :body "Your async response"} ;; false ; Uncomment to use chunk encoding for HTTP streaming )) Example - WebSocket response: (defn my-chatroom-handler [ring-req] (if-not (:websocket? ring-req) {:status 200 :body "Welcome to the chatroom! JS client connecting..."} (as-channel ring-req {:on-receive (fn [ch message] (println "on-receive:" message)) :on-close (fn [ch status-code] (println "on-close:" status-code)) :on-open (fn [ch] (println "on-open:" ch))})))

No examples yet. Be the first to add one!