среда, 14 февраля 2018 г.

clojure ring async example

;;requirements

[ring "1.6.3"]
[ring/ring-jetty-adapter "1.6.3"]
[org.clojure/core.async "0.4.474"]
[org.immutant/web "2.1.10"]

;;Jetty

(ns test01.core
  (:gen-class)
  (:require [ring.adapter.jetty :as jetty]
            [clojure.core.async :refer [go chan <! <!! >! >!! timeout close!]]))


(defn what-is-my-ip [request respond raise]
  (respond {:status  200
            :headers {"Content-Type" "text/plain"}
            :body    (:remote-addr request)}))



(defn what-is-my-ip2 [request respond raise]
  (let [ch (chan)]
    (go
      (respond (<! ch)))
    (go
      ;;(<! (timeout 2000))
      (>! ch {:status  200
              :headers {"Content-Type" "text/plain"}
              :body    (:remote-addr request)}))))

(defn start-server
  [handler]
  (jetty/run-jetty handler {:host "localhost" :async? true :port 8080 :path "/" :join? false}))


(defn -main
  "entry point"
  [& args]
  (println "Hello, world."))

;; (def s (start-server what-is-my-ip))
;; (.stop s)
;;(def s (start-server what-is-my-ip2))

;;Immutant

(ns test01.imm
  (:require [immutant.web :as web]
            [immutant.web.async :as async]))


(defn app [request]
  (async/as-channel request
                    {:on-open (fn [stream]
                                (async/send! stream {:status  200
                                                     :headers {"Content-Type" "text/plain"}
                                                     :body    (:remote-addr request)}
                                             {:close? true}))}))


(defn start-server [h]
  (web/run h {:host "localhost" :port 8080}))

(def s (start-server app))

(web/stop s)




Комментариев нет:

Отправить комментарий