Skip to content

Instantly share code, notes, and snippets.

@brunchybit
Forked from anonymous/ws.clj
Created August 21, 2012 14:33
Show Gist options
  • Save brunchybit/3416042 to your computer and use it in GitHub Desktop.
Save brunchybit/3416042 to your computer and use it in GitHub Desktop.
Example of JSON message exchange and world update in Aleph using websockets
(ns test.ws
(:use
lamina.core
compojure.core
compojure.response
aleph.core
aleph.http
aleph.formats
hiccup.core
ring.middleware.reload
ring.middleware.file
hiccup.form-helpers
ring.adapter.jetty
[ring.util.response :only (response content-type)]
)
(:require
[compojure.handler :as handler]
)
)
(def clients (agent 0))
(def broadcast-channel (named-channel :broadcast))
(def world-channel (named-channel :world))
(defn start-messaging [channel]
(enqueue world-channel {:t 0 :clients 0})
(let
[clock (sample-every 1000 world-channel)]
(receive-all clock
(fn [m] (enqueue world-channel {:t (+ (:t m) 1) :clients @clients}) )
)
(siphon world-channel channel)
)
)
(defn websocket-handler [channel request]
(println request)
(siphon (map* decode-json channel) broadcast-channel)
(siphon (map* encode-json->string broadcast-channel) channel)
(on-closed channel #(send clients dec))
(send clients inc)
)
(defn page [request]
(html
[:script
"
function openWebSocket()
{
if (window.WebSocket)
{
socket = new WebSocket('ws://localhost:8080/ws');
socket.onopen = function(event) { console.log('WebSocket open!');};
socket.onclose = function(event) { console.log('WebSocket closed'); };
socket.onmessage = function(event) { console.log(event.data);};
}
else
{
alert('Your browser does not support WebSockets yet.');
}
}
function closeWebSocket()
{
socket.close();
}
function send(message)
{
if (!window.WebSocket) { return; }
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert('The WebSocket is not open!');
}
}
"
]
[:body
[:button {:onclick "openWebSocket()"} "open"]
[:button {:onclick "closeWebSocket()"} "close"]
[:input#message {:type "text" :value "{ \"q\": 2 }"} ]
[:button {:onclick "send(document.getElementById('message').value)"} "send"]
]
)
)
(defroutes routez
(GET "/" [] page)
(GET "/ws" [] (wrap-aleph-handler websocket-handler ))
)
(start-http-server (wrap-ring-handler (handler/site routez)) {:port 8080 :websocket true})
(start-messaging broadcast-channel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment