cch1 / http.async.client

Async Http Client - Clojure
http://cch1.github.com/http.async.client
267 stars 40 forks source link

+TITLE: http.async.client - Asynchronous HTTP Client - Clojure

+SETUPFILE: org/setup.org

http.async.client is the Asynchronous HTTP Client for Clojure. It is promise-based and uses the [[http://github.com/AsyncHttpClient/async-http-client][Asynchronous Http Client for Java]] for the heavy lifting.

** Asynchronous GET request

+BEGIN_SRC clojure -n

(ns async-get (:require [http.async.client :as http]))

(with-open [client (http/create-client)] (let [response (http/GET client "https://github.com/cch1/http.async.client/")] (-> response http/await http/string)))

+END_SRC

** WebSocket client

+BEGIN_SRC clojure -n

(ns ws-client (:require [http.async.client :as http]))

(def url "ws://remote-websocket-url:1337")

(defn on-open [ws] (println "Connected to WebSocket."))

(defn on-close [ws code reason] (println "Connection to WebSocket closed.\n" (format "[%s] %s" code reason)))

(defn on-error [ws e] (println "ERROR:" e))

(defn handle-message [ws msg] (prn "got message:" msg))

(defn -main [] (println "Connecting...") (with-open [client (http/create-client)] (let [ws (http/websocket client url :open on-open :close on-close :error on-error :text handle-message)] ; this loop-recur is here as a placeholder to keep the process ; from ending, so that the message-handling function will continue to ; print messages to STDOUT until Ctrl-C is pressed (loop [] (recur)))))

+END_SRC