Skip to content

Instantly share code, notes, and snippets.

@mathyourlife
Created September 27, 2014 03:41
Show Gist options
  • Save mathyourlife/1124bb7ca1caa48f11b6 to your computer and use it in GitHub Desktop.
Save mathyourlife/1124bb7ca1caa48f11b6 to your computer and use it in GitHub Desktop.
clojure: listen to a port and parse lines

Clojure TCP Simple Server

Creates a clojure script that listens on TCP port 8000 and prints out lines received through the connection.

(require '[clojure.java.io :as io])
(import '[java.net ServerSocket])

(defn receive
  "Read a sequence of lines from the socket"
  [socket]
  (line-seq (io/reader socket)))

(defn serve [port]
  "iterate through lines received on the established TCP connection"
  (with-open [server-sock (ServerSocket. port)
              sock (.accept server-sock)]
    (doseq [msg-in (receive sock)]
      (println msg-in))))

(serve 8000)

based off sample from clojure-cookbook

Try it out

< /usr/share/dict/words nc localhost 8000

:)

@coffeemancy
Copy link

Nice work.

In code golf form:

(require '[clojure.java.io :as io])
(import '[java.net ServerSocket])

(defn serve
  "iterate through lines received on the established TCP connection"
  [port]
  (with-open [sock (.accept (ServerSocket. port))]
    (doseq [msg-in (#(line-seq (io/reader %)) sock)]
      (println msg-in))))

(serve 8000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment