in Clojure

Clojure – TCP Server Socket


(require '[ :as io])
(import '[ ServerSocket])

(defn receive
  "Read a line of textual data from the given socket"
  (.readLine (io/reader socket)))

(defn send
  "Send the given string message out over the given socket"
  [socket msg]
  (let [writer (io/writer socket)]
      (.write writer msg)
      (.flush writer)))

(defn serve [port handler]
  (with-open [server-sock (ServerSocket. port)
              sock (.accept server-sock)]
    (let [msg-in (receive sock)
          msg-out (handler msg-in)]
      (send sock msg-out))))
(serve 8888 #(.toUpperCase %))

Write a Comment