Roger, your code is not event based. I'm new to Clojure and as a small exercise I just want to create a simple chat server for telnet clients, any usable socket library is OK: * Chat messages are broadcast to all clients * When a client disconnect, all others will receive "A client has disconnected" message
Below is my code up to the moment. The problem is because there seems to be no disconnect event in server-socket, when a client disconnect the clients ref is inconsistent. (import '[java.io BufferedReader InputStreamReader OutputStreamWriter]) (use 'clojure.contrib.server-socket) (def clients (ref [])) (defn on-input [input] (println input) (doall (map (fn [out] (binding [*out* (OutputStreamWriter. out)] (println input) (flush))) @clients))) (defn echo [in out] (dosync (alter clients conj out)) (binding [*in* (BufferedReader. (InputStreamReader. in))] (loop [] (let [input (read-line)] (on-input input)) (recur)))) (.start (new Thread (fn [] (create-server 8080 echo)))) On Oct 2, 4:05 am, Roger Gilliar <ro...@gilliar.de> wrote: > > I want to write a simple socket server in Clojure. I want to perform > > some action when a client disconnects. > > ------------------------------------------- > The following code works for me. read-input returns nil if the socket > is closed (the client disconnects) > > Regards > Roger > > (defn read-input [] > (loop [result [] input (read-line)] > (if input > (if (= (first input) \#) > result > (recur (conj result input) (read-line)) > ) > nil))) > > (defn handle-client [in out] > (binding [ > *in* (reader in) > ] > (with-connection db > (let [outstream (writer out)] > (loop [] > (let [xml (read-input)] > (if xml > (do > (send-answers > (parse outstream (makestr xml))) > (recur)) > (info > "disconnected")))))))) > > (def server (create-server *port* handle-client)) > > Am 01.10.2009 um 20:39 schrieb ngocdaothanh: --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---