connections.clj

Bowmap · bowmap.git · Tickets

Branches > main > 88faa97 > files / src / net / bowmap / server / runtime / connections.clj

(ns net.bowmap.server.runtime.connections
  (:require
   [net.bowmap.server.network.connection :as connection]
   [net.bowmap.server.network.server :as server]
   [net.bowmap.server.protocol.packet-serialization :as serialize]
   [net.bowmap.server.protocol.phase :as phase]
   [net.bowmap.server.runtime.packets :as packets]))

(defn handle-connection! [connection]
  (let [client (atom {::phase/phase ::phase/handshaking})
        player (atom {})
        send-packet! (fn [packet]
                       (connection/send-frame! connection (serialize/encode-packet @client packet)))]
    (loop []
      (when-some [frame (connection/receive-frame!! connection)]
        (let [c @client
              packet (serialize/decode-frame c frame)
              [client' packets] (packets/apply-packet c packet)]
          (assert (compare-and-set! client c client'))
          (let [[player' packets] (packets/handle-packet @player packet)]
            (reset! player player')
            (run! send-packet! packets))
          (recur))))))

(defn handle-connections!
  [server]
  (loop []
    (let [connection (server/accept-connection!! server)]
      (Thread/startVirtualThread
        #(handle-connection! connection))
      (recur))))