Created
September 24, 2010 05:16
-
-
Save amalloy/594895 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(import [java.io PrintStream] | |
[java.util Scanner] | |
[java.net ServerSocket]) | |
(use '[clojure set]) | |
(defn serve | |
[service port] | |
(let [server (ServerSocket. port)] | |
(while (not (.isClosed server)) | |
(let [sock (.accept server)] | |
(future (service sock)))))) | |
(comment | |
(defn echo [sock] | |
(let [in (Scanner. (.getInputStream sock)) | |
out (PrintStream. (.getOutputStream sock))] | |
(while (.hasNextLine in) | |
(.println out (.nextLine in))))) | |
) | |
(defn chat-serve [port] | |
(let [clients (atom #{})] | |
(serve | |
(fn [sock] | |
(swap! clients conj sock) | |
(let [in (Scanner. (.getInputStream sock))] | |
(while (.hasNextLine in) | |
(doseq [line [(.nextLine in)] | |
out (map #(PrintStream. (.getOutputStream %)) | |
(difference @clients [sock]))] | |
(.println out line)))) | |
(swap! clients difference [sock])) | |
port))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment