A simple example of WebSockets in Aleph

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com

This looks good, and I plan to go back and study it more:

(ns core.main
(:use lamina.core
(hiccup core page))
; This sets the correct file type for js includes used by hiccup
(ring.middleware resource file-info)
(:require [compojure.route :as route])

(defn page []
“HTML page rendered using Hiccup. Includes the js we need for websockets.”
(include-css "/static/stylesheets/master.css")]
[:p [:h1#headline "Chat"]]
[:input#message {:type "text"}]
[:input.nice.large.blue.button {:type "submit"}]]
(include-js “http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”)
(include-js “/static/javascripts/web_socket.js”)
(include-js “/static/javascripts/app.js”)]))

(defn sync-app [request]
“Rendered response of the chat page”
{:status 200
:headers {“content-type” “text/html”}
:body (page)})

(def wrapped-sync-app
“Wraps the response with static files”
(-> sync-app
(wrap-resource “public”)

(defn chat-init [ch]
“Initialize a new chat channel”
(receive-all ch #(println “message: ” %)))

(defn chat-handler [ch room]
“Relays messages into a chat room. If it doesn’t
exist create a new channel”
(let [chat (named-channel room chat-init)]
(siphon chat ch)
(siphon ch chat)))

(defn chat [ch request]
“View handler that handles a chat room. If it’s not
a websocket request then return a rendered html response.”
(let [params (:route-params request)
room (:room params)]
(if (:websocket request)
(chat-handler ch room)
(enqueue ch (wrapped-sync-app request)))))

(defroutes app-routes
“Routes requests to their handler function. Captures dynamic variables.”
(GET ["/chat/:room", :room #"[a-zA-Z]+”] {}
(wrap-aleph-handler chat))
(GET ["/"] {} “Hello world!”)
;;Route our public resources like css and js to the static url
(route/resources “/static”)
;;Any url without a route handler will be served this response
(route/not-found “Page not found”))

(defn -main [& args]
“Main thread for the server which starts an async server with
all the routes we specified and is websocket ready.”
(start-http-server (wrap-ring-handler app-routes)