Basic working ClojureScript/ws server

This commit is contained in:
Nicholas Kariniemi 2013-07-24 21:38:14 +03:00
parent 77c8d55a31
commit 8651953920
3 changed files with 43 additions and 27 deletions

View file

@ -8,7 +8,8 @@
[http-kit "2.1.5"]
[compojure "1.1.5"]
[ring/ring-devel "1.2.0"]
[ring/ring-core "1.2.0"]]
[ring/ring-core "1.2.0"]
[hiccup "1.0.4"]]
:plugins [[lein-cljsbuild "0.3.2"]
[lein-ring "0.8.6"]]
:cljsbuild {
@ -21,4 +22,5 @@
:output-to "public/js/main.js" ; default: target/cljsbuild-main.js
:optimizations :whitespace
:pretty-print true}}]}
:ring {:handler grub.core/async-handler})
:ring {:handler grub.core/app}
:main grub.core)

1
public/index.html Normal file
View file

@ -0,0 +1 @@
index.html

View file

@ -1,31 +1,44 @@
(ns grub.core
(:use [org.httpkit.server :only [run-server]])
(:use [org.httpkit.server
:only [run-server with-channel on-receive send! websocket?]]
[compojure.handler :only [site]]
[compojure.core :only [defroutes GET POST]])
(:require [ring.middleware.reload :as reload]
[compojure.handler :only [site]]
[compojure.core :only [defroutes GET POST]]))
[compojure.route :as route]
[hiccup
[page :refer [html5]]
[page :refer [include-js]]]))
(defn async-handler [request]
(if-not (:websocket? request)
{:status 200 :body "WebSocket server"}
(with-channel request channel
(on-receive channel (fn [data]
(send! channel data)))
(send! channel {:status 200
:headers {"Content-Type" "text/plain"}
:body "Long polling?"}))))
(defn index-page []
(html5
[:head
[:title "Hello World"]
(include-js "/js/main.js")]
[:body
[:h3 "Grub"]]))
(defroutes routes
(GET "/" [] "handling-page")
(GET "/save" [] handler) ;; websocket
(route/not-found "<p>Page not found.</p>")) ;; all other, return 404
(GET "/ws" [] async-handler)
(GET "/" [] (index-page))
(route/files "/")
(route/not-found "<p>Page not found.</p>"))
(defn -main [& args] ;; entry point, lein run will pick up and start from here
(let [handler (if (in-dev? args)
(reload/wrap-reload (site #'routes)) ;; only reload when dev
(site routes))]
(run-server handler {:port 8080})))
(def app
(let [dev? true]
(if dev?
(reload/wrap-reload (site #'routes))
(site routes))))
(comment
(defn async-handler [ring-request]
(with-channel ring-request channel
(if (websocket? channel)
(println "WebSocket channel")
(println "HTTP channel"))
(on-receive channel (fn [data]
(send! channel data)))
(send! channel {:status 200
:headers {"Content-Type" "text/plain"}
:body "Long polling?"})))
(run-server async-handler {:port 8080})
)
(defn -main [& args]
(run-server app {:port 8080}))