server.clj

Branches > facts > 2190c63 > files / src / net / bowmap / network / server.clj

(ns net.bowmap.network.server
  (:require
   [clojure.core.async :refer [<!! alt!! io-thread]]
   [net.bowmap.network.client :as client :refer [send-packet!!]]
   [net.bowmap.network.connection :as connection]
   [net.bowmap.network.handle :as handle]
   [net.bowmap.network.minecraft-server :as mc]
   [net.bowmap.network.packets.serverbound :refer [decode-packet!]]
   [net.bowmap.network.state :as state]))

(defn handle-connection [connection]
  (io-thread
    (try
      (let [client (client/client connection)
            clientbound-packets (req! client ::client/clientbound-packets)
            serverbound-frames (req! connection ::connection/serverbound-frames)]
        (loop [client client]
          (alt!!
            serverbound-frames ([frame]
                                (when (some? frame)
                                  (recur (handle/handle!! client (decode-packet! frame (::state/connection-state client))))))
            clientbound-packets ([pk]
                                 (if (some? pk)
                                   (do (send-packet!! client pk)
                                       (recur client))
                                   (throw (Exception. "Clientbound packets was closed idk why")))))))
      (finally
        ; TODO Send player disconnected fact, and update the player list from that
        (connection/close! connection)))))

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