core.clj

Branches > main > 0190c10 > files / src / net / bowmap / core.clj

(ns net.bowmap.core
  (:require
   [clojure.core.async :refer [<!! >!! alt!! chan io-thread put! timeout]]
   [net.bowmap.client.state :as state]
   [net.bowmap.packet :as pk]
   [net.bowmap.packet-handling :as handle]
   [net.bowmap.packet.client :as cp]
   [net.bowmap.packet.server :as sp]
   [net.bowmap.server :as server]))

(defn handle-packet
  "Handles one ByteBuf of a framed serialized serverbound packet, and returns a
   map of :client and :packets."
  [client packet-buf]
  (let [pk (sp/decode-packet packet-buf (::state/state client))]
    (handle/response client pk)))

(defn handle-something-or-other [client in packets-out out]
  (alt!!
    in ([buf]
        (when buf
          (let [response (handle-packet client buf)]
            (when (:keepalive response)
              (io-thread
                (loop []
                  (<!! (timeout 5000))
                  (when (>!! packets-out {::pk/id ::cp/keep-alive
                                          :id (long (* (rand) Long/MAX_VALUE))})
                    (recur)))))
            (doseq [pk (:response response)]
              (put! packets-out pk))
            (:client response))))
    packets-out ([pk]
                 (assert (>!! out (cp/encode-packet pk (::state/state client))))
                 client)))

; Do I need to close out?
(defn client-handler [in out]
  (let [packets-out (chan)
        client {::state/state ::state/handshaking}]
    (try (loop [client client]
           (when-some [client (handle-something-or-other client in packets-out out)]
             (recur client)))
         (catch Throwable e (println "In client handler: " e)))))

(defn start-server []
  (server/start-server2! {:handler #'client-handler
                          :port 25565}))

(defn -main [& _args]
  (start-server)
  (println "Server Started"))

(comment
  (def server (start-server))
  (.close server))