--- layout: doc title: HTTP server ---

Ring adapter(HTTP server) with async and websocket extension

{% highlight clojure %} (:use org.httpkit.server) {% endhighlight %}

The server uses an event-driven, non-blocking I/O model that makes it lightweight and scalable. It's written to conform to the standard Clojure web server Ring spec, with asynchronous and websocket extension. HTTP Kit is (almost) drop-in replacement of ring-jetty-adapter

Hello, Clojure HTTP server

run-server starts a Ring-compatible HTTP server. You may want to do routing with compojure

{% highlight clojure %} (defn app [req] {:status 200 :headers {"Content-Type" "text/html"} :body "hello HTTP!"}) (run-server app {:port 8080}) {% endhighlight %}

Options:

Stop/Restart Server

run-server returns a function that stops the server, which can take an optional timeout(ms) param to wait for existing requests to be finished.

{% highlight clojure %} (defn app [req] {:status 200 :headers {"Content-Type" "text/html"} :body "hello HTTP!"}) (defonce server (atom nil)) (defn stop-server [] (when-not (nil? @server) ;; graceful shutdown: wait 100ms for existing requests to be finished ;; :timeout is optional, when no timeout, stop immediately (@server :timeout 100) (reset! server nil))) (defn -main [& args] ;; The #' is useful when you want to hot-reload code ;; You may want to take a look: https://github.com/clojure/tools.namespace ;; and https://http-kit.github.io/migration.html#reload (reset! server (run-server #'app {:port 8080}))) {% endhighlight %}

Unified Async/Websocket API

The with-channel API is not compatible with the RC releases. The new one is better and much easier to understand and use. The old documentation is here

Unified asynchronous channel interface for HTTP (streaming or long-polling) and WebSocket.

Channel defines the following contract: {% highlight clojure %} (defn handler [req] (with-channel req channel ; get the channel ;; communicate with client using method defined above (on-close channel (fn [status] (println "channel closed"))) (if (websocket? channel) (println "WebSocket channel") (println "HTTP channel")) (on-receive channel (fn [data] ; data received from client ;; An optional param can pass to send!: close-after-send? ;; When unspecified, `close-after-send?` defaults to true for HTTP channels ;; and false for WebSocket. (send! channel data close-after-send?) (send! channel data))))) ; data is sent directly to the client (run-server handler {:port 8080}) {% endhighlight %}

HTTP Streaming example

{% highlight clojure %} (use 'org.httpkit.timer) (defn handler [request] (with-channel request channel (on-close channel (fn [status] (println "channel closed, " status))) (loop [id 0] (when (< id 10) (schedule-task (* id 200) ;; send a message every 200ms (send! channel (str "message from server #" id) false)) ; false => don't close after send (recur (inc id)))) (schedule-task 10000 (close channel)))) ;; close in 10s. ;;; open you browser http://127.0.0.1:9090, a new message show up every 200ms (run-server handler {:port 9090}) {% endhighlight %}

Long polling example

Long polling is very much like streaming

chat-polling is a realtime chat example of using polling

{% highlight clojure %} (def channel-hub (atom {})) (defn handler [request] (with-channel request channel ;; Store the channel somewhere, and use it to send response to client when interesting event happens (swap! channel-hub assoc channel request) (on-close channel (fn [status] ;; remove from hub when channel get closed (swap! channel-hub dissoc channel))))) (on-some-event ;; send data to client (doseq [channel (keys @channel-hub)] (send! channel {:status 200 :headers {"Content-Type" "application/json; charset=utf-8"} :body data}))) (run-server handler {:port 9090}) {% endhighlight %}

WebSocket example

{% highlight clojure %} (defn handler [request] (with-channel request channel (on-close channel (fn [status] (println "channel closed: " status))) (on-receive channel (fn [data] ;; echo it back (send! channel data))))) (run-server handler {:port 9090}) {% endhighlight %}

Control WebSocket handshake

The with-channel does the WebSocket handshake automatically. In case if you want to control it, e.g., to support WebSocket subprotocol, here is a workaround. cgmartin's gist is a good place to get inspired.

Routing with Compojure

Compojure can be used to do the routing, based on uri and method

{% highlight clojure %} (:use [compojure.route :only [files not-found]] [compojure.core :only [defroutes GET POST DELETE ANY context]] org.httpkit.server) (defn show-landing-page [req] ;; ordinary clojure function, accepts a request map, returns a response map ;; return landing page's html string. Using template library is a good idea: ;; mustache (https://github.com/shenfeng/mustache.clj, https://github.com/fhd/clostache...) ;; enlive (https://github.com/cgrand/enlive) ;; hiccup(https://github.com/weavejester/hiccup) ) (defn update-userinfo [req] ;; ordinary clojure function (let [user-id (-> req :params :id) ; param from uri password (-> req :params :password)] ; form param .... )) (defroutes all-routes (GET "/" [] show-landing-page) (GET "/ws" [] chat-handler) ;; websocket (GET "/async" [] async-handler) ;; asynchronous(long polling) (context "/user/:id" [] (GET / [] get-user-by-id) (POST / [] update-userinfo)) (files "/static/") ;; static file url prefix /static, in `public` folder (not-found "

Page not found.

")) ;; all other, return 404 (run-server all-routes {:port 8080}) {% endhighlight %}

Recommended server deployment

http-kit runs alone happily, handy for development and quick deployment. Use of a reverse proxy like Nginx, Lighthttpd, etc in serious production is encouraged. They can also be used to add https support.

Sample Nginx configration:

{% highlight sh %} upstream http_backend { server 127.0.0.1:8090; # http-kit listen on 8090 # put more servers here for load balancing # keepalive(resue TCP connection) improves performance keepalive 32; # both http-kit and nginx are good at concurrency } server { location /static/ { # static content alias /var/www/xxxx/public/; } location / { proxy_pass http://http_backend; # tell http-kit to keep the connection proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; access_log /var/log/nginx/xxxx.access.log; } } {% endhighlight %}