From c4f18a4392ec4203adbba4c5300456cfa2842abd Mon Sep 17 00:00:00 2001 From: Chris O'Donnell Date: Tue, 12 May 2015 18:51:26 -0400 Subject: [PATCH] Implement reconnect. --- src/irclj/core.clj | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/irclj/core.clj b/src/irclj/core.clj index 9a1f68a..07ff233 100644 --- a/src/irclj/core.clj +++ b/src/irclj/core.clj @@ -110,6 +110,7 @@ (defn quit [irc] + (dosync (alter irc assoc :reconnect? false)) (connection/write-irc-line irc "QUIT")) ;; We fire our raw-log callback for the lines we read from IRC as well. @@ -119,16 +120,27 @@ (events/fire irc :raw-log :read line) (process/process-line (parser/parse line) irc)) +(defn- reconnect [irc port ssl? timeout] + (let [host (:network @irc)] + (prn "Reconnecting...") + (dosync + (alter irc assoc + :connection (connection/create-connection host port ssl?) + :ready? (promise))) + (connection/set-timeout irc timeout) + (connection/register-connection irc))) + (defn connect "Connect to IRC. Connects in another thread and returns a big fat ref of data about the connection, you, and IRC in general." [host port nick & - {:keys [pass timeout real-name mode username callbacks ssl?] + {:keys [pass timeout real-name mode username callbacks ssl? reconnect?] :or {real-name "irclj", mode 0, ssl? false callbacks {:raw-log events/stdout-callback}} :as all}] (let [{:keys [in] :as connection} (connection/create-connection host port ssl?) irc (ref {:connection connection + :reconnect? reconnect? :shutdown? false :prefixes {} :pass pass @@ -149,7 +161,12 @@ (if-let [line (first lines)] (do (process irc line) (recur (rest lines))) - (events/fire irc :on-shutdown))) + (if (:reconnect? @irc) + (do (reconnect irc port ssl? timeout) + (.start (Thread. (fn [] (when (:ready? @irc) + (events/fire irc :on-reconnect))))) + (recur (connection/safe-line-seq (get-in @irc [:connection :in])))) + (events/fire irc :on-shutdown)))) (catch Exception e (deliver (:ready? @irc) false) ;; unblock the promise (events/fire irc :on-exception e) @@ -160,4 +177,5 @@ (defn kill "Close the socket associated with an IRC connection." [irc] + (dosync (alter irc assoc :reconnect? false)) (.close (get-in @irc [:connection :socket])))