Skip to content

Instantly share code, notes, and snippets.

@certainty
Last active August 29, 2015 13:56
Show Gist options
  • Save certainty/9212223 to your computer and use it in GitHub Desktop.
Save certainty/9212223 to your computer and use it in GitHub Desktop.
(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
Copy link

(defn read-until-match [seq rx]
  (loop [seq (rest seq)
         buffer (str (first seq))]
    (when-not (re-find rx buffer)
      (println "read sofar " buffer)
      (recur (rest seq) (str (first seq) buffer)))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment