keepalive.clj

Branches > main > 4b378ce > files / src / net / bowmap / protocol / keepalive.clj

(ns net.bowmap.protocol.keepalive
  (:require
   [clojure.core.async :refer [<!! io-thread put! timeout]]
   [net.bowmap.protocol.client :as client]
   [net.bowmap.protocol.packet :as pk]
   [net.bowmap.protocol.packet.clientbound :as clientbound]))

; TODO this takes a snapshot of the clients value...
(defonce keepalive-clients (ref #{}))
(defonce running? (atom false))

(defn keep-alive! [client]
  (dosync
    (commute keepalive-clients conj client)))

(defn start-keep-alives! []
  (when-not @running?
    (reset! running? true)
    (io-thread
      (loop []
        (<!! (timeout 20000))
        (doseq [{::client/keys [clientbound-packets] :as client} @keepalive-clients]
          (put! clientbound-packets {::pk/id ::clientbound/keep-alive
                                     :id (rand-int Integer/MAX_VALUE)})
          (fn [result]
            (when-not result
              (dosync
                (commute keepalive-clients disj client)))))
        (recur)))))