« back

Adding conditions to the Clojure Echo Server

27 Nov 2012

After successfully getting an echo server running, it's time to spice things up by adding some conditions.

If you are coming into this post without context, you may want to read this and then this first.

Doug presented me with two ways to change it up. 1. I could have my server answer 42 to the question "What is the meaning of life?" 2. I could quit when quit is typed and I could issue a response when I was quitting. The code I was starting with was this.

 1 (ns echo_server.core
 2 	(:use server.socket))
 3 (import '[java.io BufferedReader InputStreamReader OutputStreamWriter])
 4 
 5 (def port 1234)
 6 
 7 (defn echo-server [in out]
 8 	(binding [*in* (BufferedReader. (InputStreamReader. in))
 9 			  *out* (OutputStreamWriter. out)]
10 		(loop []
11 			(println (read-line))
12 			(recur))))
13 
14 (defn -main []
15 (create-server port echo-server))

This time when we use loop, we want to use recur. We will set a binding. [input (read-line)]. We will also want to set up some conditions and print something according to the input. After printing, if the input was not quit, we will want to call recur. If it was quit, we will simply print out goodbye and then never call recur. Something to be pointed out is the isolation of the printing from the calling of recur.

 1 (defn echo-server [in out]
 2 	(binding [*in* (BufferedReader. (InputStreamReader. in))
 3 			  *out* (OutputStreamWriter. out)]
 4 		(loop [input (read-line)]
 5 			(println 
 6 			    (cond (= "quit" input) "goodbye."
 7 				      (= "what is the meaning of life?" input) "42"
 8 				      :else input))
 9 			    (if (not= "quit" input) (recur (read-line))))))
10 
11 (defn -main []
12 (create-server port echo-server))

I set a binding in jekyll and it's time for me to (recur (write_next_blog_post)) ! :)

comments powered by Disqus