Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a multiplexing server in clojure?

Tags:

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?

like image 532
horseyguy Avatar asked Aug 03 '09 16:08

horseyguy


1 Answers

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/

like image 77
alanlcode Avatar answered Sep 23 '22 17:09

alanlcode