Skip to content

Commit

Permalink
Added a UDP cli server.
Browse files Browse the repository at this point in the history
  • Loading branch information
ryugi committed May 31, 2017
1 parent f4898df commit 801b492
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 2 deletions.
4 changes: 3 additions & 1 deletion project.clj
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@
[ring/ring-codec "1.0.1"]
[ring/ring-core "1.6.1"]
[selmer "1.10.7" :exclusions [joda-time]]
[systems.billo/net "0.3.3-beta12-Clojure1.8"]]
[systems.billo/inet-address "0.1.0"]
[systems.billo/net "0.3.3-beta12-Clojure1.8"]
[systems.billo/sockets "0.1.0"]]
:plugins [
[cider/cider-nrepl "0.10.0"]
[lein-cljsbuild "1.1.4" :exclusions [[org.clojure/clojure]]]
Expand Down
78 changes: 78 additions & 0 deletions src/clj/timi/server/cli/udp.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
(ns timi.server.cli.udp
(:require
[clojure.core.async :as async]
[inet.address :as inet]
[sockets.datagram.packet :as packet]
[sockets.datagram.socket :as socket]
[taoensso.timbre :as log]
[timi.server.cli.core :as cli])
(:import
(clojure.lang Keyword)
(java.net SocketException)))

(def max-packet-size 4096)

(defmulti ->bytes type)

(defmethod ->bytes String
[text]
(let [bytes (.getBytes text "UTF-8")]
(byte-array (count bytes) bytes)))

(defmethod ->bytes Keyword
[data]
(->bytes (str data)))

(defn bytes->str
[data]
(new String data "UTF-8"))

(defn cli-service
[in out]
(async/go-loop []
(let [dest (async/<! in)]
(async/>! out dest)
(recur))))

(defn receive
[sock]
(try
(socket/receive sock max-packet-size)
(catch SocketException e nil)))

(defn packet-reader
[sock]
(let [in (async/chan)]
(async/go-loop []
(when-let [pkt (receive sock)]
(async/>! in {:remote-addr (packet/address pkt)
:remote-port (packet/port pkt)
:command (bytes->str (packet/data pkt))})
(recur)))
in))

(defn cli-writer
[config sock]
(let [out (async/chan)]
(async/go-loop []
(let [msg (async/<! out)
pkt-text (cli/run config (:command msg))
pkt-data (->bytes pkt-text)
pkt (packet/create pkt-data
(count pkt-data)
(:remote-addr msg)
(:remote-port msg))]
(socket/send sock pkt))
(recur))
out))

(defn serve
[config]
(let [sock (-> config
(get-in [:cli :server :port])
(socket/create))
in (packet-reader sock)
out (cli-writer config sock)]
(async/go
(cli-service in out))
(fn [] (socket/close sock))))
2 changes: 1 addition & 1 deletion src/clj/timi/server/components/cli.clj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
(:require
[com.stuartsierra.component :as component]
[taoensso.timbre :as log]
[timi.server.cli.tcp :as cli-server]))
[timi.server.cli.udp :as cli-server]))

(defrecord CLIServer []
component/Lifecycle
Expand Down

0 comments on commit 801b492

Please sign in to comment.