Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure (aleph) detecting when server disconnects

I have the following code:

(ns alephtest.core             
    (:use lamina.core aleph.tcp aleph.formats))

(defn connection-established [socket] 
    (println "Socket connection established")
    (on-closed socket #(println "closed"))
    (doseq [line (line-seq (java.io.BufferedReader. *in*))]
        (enqueue socket line)))

(defn -main [] 
    (on-realized (tcp-client {:host "localhost" :port 9000}) 
        connection-established 
        #(println "error:" %)))

All it does right now is connects to a local server and then passes data from stdin through to the server. This works fine, except for the (on-closed socket #(println "closed")) portion. If I kill the server while the client is still going I should get a message saying "closed" to the console, but I never do.

My end-goal here is to create some kind of recovery code, so that if the server goes down the client will queue up messages while it waits for the server to come back, and when the server does come back it'll reconnect and send everything that was queued.

like image 879
Mediocre Gopher Avatar asked Nov 09 '12 22:11

Mediocre Gopher


1 Answers

It looks like you're blocking the thread that would notify you of the socket closing with your (doseq ...) loop. Wrap that in a (future ...), and see if that doesn't fix it.

like image 95
ztellman Avatar answered Sep 24 '22 07:09

ztellman