I would like to write a simple multiplexing server in Clojure (as a sample project to learn the language) but I am having a very hard time finding resources to aid me in this on the web.
does anyone have any resources that can point to the basics of socket programming in Clojure and the best way to go about writing such a server?
clojure.contrib.server-socket
is your friend. Use create-server
like so to create a simple echo server:
(import '[java.io BufferedReader InputStreamReader OutputStreamWriter]) (use 'clojure.contrib.server-socket) (defn echo-server [] (letfn [(echo [in out] (binding [*in* (BufferedReader. (InputStreamReader. in)) *out* (OutputStreamWriter. out)] (loop [] (let [input (read-line)] (print input) (flush)) (recur))))] (create-server 8080 echo))) (def my-server (echo-server))
Now telnet to make sure it works:
$ telnet localhost 8080 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hello hello // this is the echoed line, woohoo!
By the way, the server is multithreaded too, because clojure.contrib.server-socket
creates a new thread on accepting a new connection.
If that doesn't meet your needs, then the Java API is your friend. Since you have full access to Java classes from Clojure, you can just use Java sockets if you need to get down to the metal. I don't know anything about your background, but assuming you have not used Java sockets before, Sun has a tutorial: http://java.sun.com/docs/books/tutorial/networking/sockets/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With