Skip to content

Instantly share code, notes, and snippets.

@swannodette
Created December 7, 2009 20:51
Show Gist options
  • Select an option

  • Save swannodette/251096 to your computer and use it in GitHub Desktop.

Select an option

Save swannodette/251096 to your computer and use it in GitHub Desktop.
(defn start-server-socket!
"Given a `server-socket' (java.net.ServerSocket), call
`handle-socket' for each new connection and provide current
socket.
`multiple-connections?' defines whether multiple connections can be
made to this socket server (default: true).
This will return immediately with the Thread that is blocking for
new connections. Use Thread.join() if you need to wait for the
server to close."
([server-socket handle-socket]
(start-server-socket! server-socket handle-socket true))
([server-socket handle-socket multiple-connections?]
(dothread-keeping-clj nil ; <============================= FAILS HERE !
(thread-set-name (str "Socket Server [" (thread-id) "]"))
(with-open [#^ServerSocket server server-socket]
(try
(if multiple-connections?
(while (not (.isClosed server))
(handle-socket (.accept server)))
(handle-socket (.accept server))))))))
; --->
(defmacro dothread-keeping [bindings & body]
`(start-thread (keep-bindings ~bindings (fn [] ~@body))))
(defmacro dothread-keeping-clj [more-bindings & body]
(let [clj-star-syms (filter #(.startsWith #^String (name %) "*")
(keys (ns-publics (find-ns 'clojure.core))))]
`(dothread-keeping [~@clj-star-syms ~@more-bindings]
~@body)))
; --->
(defmacro keep-bindings [bindings f]
(let [bind-vars (take (count bindings) (repeatedly gensym))]
`(let [~@(interleave bind-vars bindings)]
(fn [& args#]
(binding [~@(interleave bindings bind-vars)]
(apply ~f args#))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment