views:

1142

answers:

3

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?

+1  A: 

Check out clojure.contrib to see if there are any libraries for manipulating sockets. If there aren't, then you're left with writing your own by using Java classes through Clojure's Java interop facilities.

Pinochle
+13  A: 

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/

alanlcode
beautiful! thanks :)
banister
+5  A: 

I wrote a small multiplayer text adventure game called Mire that demonstrates this. It's pretty straightforward.

technomancy