Last active
August 29, 2015 13:56
-
-
Save certainty/9212223 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
(defn with-connection [host port fn] | |
(with-open [sock (Socket. host port) | |
writer (io/writer sock) | |
reader (io/reader sock)] | |
;; handle errors | |
(fn reader writer))) | |
(defn- read-with-timeout | |
"Reads a single byte from reader or returns false if it | |
could not be read within the given timeout in milliseconds | |
" | |
[rdr timeout] | |
(let [end (+ (System/currentTimeMillis) timeout)] | |
(loop [] | |
(if (.ready rdr) | |
(.read rdr) | |
(and (< (System/currentTimeMillis) end) | |
(recur)))))) | |
(defn lazy-reader-with-timeout | |
"Create a lazy-seq that reads a byte at a time | |
and throws an exception if a read did not return | |
data within the given timeout (in millisecs) | |
" | |
[rdr timeout] | |
(let [byte (read-with-timeout rdr timeout)] | |
(if byte | |
(when (>= byte 0) | |
(cons byte (lazy-seq (lazy-reader-with-timeout rdr timeout)))) | |
(throw (Exception. "Timeout accured"))))) | |
(defn read-until-match [seq rx] | |
(let [read-char (comp str char first)] | |
(loop [seq (rest seq) | |
buffer (read-char seq)] | |
(when-not (re-find rx buffer) | |
(println "read sofar " buffer) | |
(recur (rest seq) (str buffer (read-char seq))))))) | |
;; example usage | |
(defn handler [timeout] | |
(fn [r w] | |
(let [seq (lazy-reader-with-timeout r timeout)] | |
(read-until-match seq #"console")))) | |
(with-connection "localhost" 12345 (handler 5000)) |
DerGuteMoritz
commented
Feb 25, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment