Sir Robert
Sir Robert

Reputation: 4946

How can I handle websocket disconnect (from page reload) in Aleph?

I've written an event-based websocket handler using aleph. The core file looks like this:

(defn handle-message
  "Handle a message"
  [message]
  (event/dispatch message))

(defn websocket-handler
  "Handle websocket connections."
  [client-node connection-data]
  (map* #(handle-message (message/create client-node connection-data %)) client-node))

(defn -main
  "Start the http server and start handling websocket connections."
  [& args]
  (myapp.routes.api/add-events)
  (start-http-server websocket-handler {:port 8080 :websocket true}))

This works fine and I have some events that work and give expected output. When I reload a page, it stops working. What's the problem? I assume there's a disconnect/reconnect happening. How can I manage disconnects on the server side?

Upvotes: 1

Views: 500

Answers (1)

Hendekagon
Hendekagon

Reputation: 4643

In your function for clients connecting, add a fn to handle what to do when their end of the channel closes:

(defn connection-handler [channel request]
 (lamina/on-closed channel handle-client-disconnected-fn)
)

(defroutes my-routes
  (GET "/my-website-path" [] (wrap-aleph-handler connection-handler))
)

(start-http-server
    (->
      my-routes
      (wrap-session)
      (wrap-file "./public")
      (wrap-file-info)
      (wrap-stacktrace)
      (wrap-ring-handler)
    )
    {:port 8080 :websocket true}
)

edit: in practice, check they aren't already connected so you don't add the handler more than once

Upvotes: 2

Related Questions