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"] [http-kit "2.1.5"]
[compojure "1.1.5"] [compojure "1.1.5"]
[ring/ring-devel "1.2.0"] [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"] :plugins [[lein-cljsbuild "0.3.2"]
[lein-ring "0.8.6"]] [lein-ring "0.8.6"]]
:cljsbuild { :cljsbuild {
@ -21,4 +22,5 @@
:output-to "public/js/main.js" ; default: target/cljsbuild-main.js :output-to "public/js/main.js" ; default: target/cljsbuild-main.js
:optimizations :whitespace :optimizations :whitespace
:pretty-print true}}]} :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 (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] (:require [ring.middleware.reload :as reload]
[compojure.handler :only [site]] [compojure.route :as route]
[compojure.core :only [defroutes GET POST]])) [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 (defroutes routes
(GET "/" [] "handling-page") (GET "/ws" [] async-handler)
(GET "/save" [] handler) ;; websocket (GET "/" [] (index-page))
(route/not-found "<p>Page not found.</p>")) ;; all other, return 404 (route/files "/")
(route/not-found "<p>Page not found.</p>"))
(defn -main [& args] ;; entry point, lein run will pick up and start from here (def app
(let [handler (if (in-dev? args) (let [dev? true]
(reload/wrap-reload (site #'routes)) ;; only reload when dev (if dev?
(site routes))] (reload/wrap-reload (site #'routes))
(run-server handler {:port 8080}))) (site routes))))
(comment (defn -main [& args]
(defn async-handler [ring-request] (run-server app {:port 8080}))
(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})
)