суббота, 22 сентября 2018 г.

clojure websocket client example

This is my deps.edn
https://github.com/middlesphere/spacemacs-clojure-cheatsheet/blob/master/.clojure/deps.edn

1) Start REPL with necessary deps.

clojure -R:1.10:repl:add-lib:test:debug-tools:rebel:xml-bind -m nrepl.cmdline -p 7888 -i -m "[refactor-nrepl.middleware/wrap-refactor,cider.nrepl/cider-middleware]"
nREPL server started on port 7888 on host 0:0:0:0:0:0:0:0 - nrepl://0:0:0:0:0:0:0:0:7888
nREPL 0.4.5
Clojure 1.10.0-alpha8
Java HotSpot(TM) 64-Bit Server VM 10.0.2+13
user=> (use 'clojure.tools.deps.alpha.repl)
nil
user=> (add-lib 'stylefruits/gniazdo {:mvn/version "1.0.1"})
true
user=> (add-lib 'http-kit {:mvn/version "2.2.0"})
true

2) Create empty file (e.g a.clj), connect to REPL (port 7888)  and put following code there:

;; ------------server code --------------------

(use 'org.httpkit.server)

(defn async-handler [ring-request]
  ;; unified API for WebSocket and HTTP long polling/streaming
  (with-channel ring-request channel    ; get the channel
    (if (websocket? channel)            ; if you want to distinguish them
      (on-receive channel (fn [data]     ; two way communication
                            (send! channel data)))
      (send! channel {:status  200
                      :headers {"Content-Type" "text/plain"}
                      :body    "Long polling?"}))))

(run-server async-handler {:port 8080})

;; ------------client code --------------------

(require '[gniazdo.core :as ws])

(def socket (ws/connect "ws://localhost:8080/" :on-receive #(prn 'received %)))
(ws/send-msg socket "hello")
(ws/send-msg socket "world")

(ws/close socket)

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

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