server.clj

Branches > main > 1fcddae > files / src / net / bowmap / protocol / server.clj

(ns net.bowmap.protocol.server
  (:require
   [clojure.core.async :refer [<!! io-thread put!]]
   [net.bowmap.protocol.handle :as handle]
   [net.bowmap.server.logic :as logic]
   [net.bowmap.server.player :as player]
   [net.bowmap.stormbow.effect-execution :refer [execute-effects!]]
   [net.bowmap.stormbow.event :as event]
   [net.bowmap.transport.connection :as connection]
   [net.bowmap.transport.server :as mc]))

(defn connection-lifecycle [connection]
  (let [{::connection/keys! [serverbound-packets clientbound-packets]} connection]
    (loop []
      (let [{:keys [packets events]} (handle/interpret-packet (<!! serverbound-packets))]
        (doseq [packet packets]
          (put! clientbound-packets packet))
        (doseq [event events]
          (execute-effects! (logic/handle-events event))))
      (recur))))

(defn handle-connection [connection]
  (io-thread
    (let [{::connection/keys! [close-fn closed]} connection]
      (io-thread
        (when-let [uuid @closed]
          (execute-effects! (logic/handle-events {::event/id ::event/player-left ::player/uuid uuid}))))
      (try
        (connection-lifecycle connection)
        (finally
          (close-fn))))))

(defn start-server! [port]
  (let [connections (mc/start-server! port)]
    (loop []
      (when-let [connection (<!! connections)]
        (handle-connection connection))
      (recur))))