core.clj

Branches > client-handling-rewrite > 0880c86 > files / src / net / bowmap / core.clj

(ns net.bowmap.core
  (:require
   [clojure.core.async :refer [<!! >!! alt!! chan io-thread put! timeout]]
   [net.bowmap.network.message :as msg]
   [net.bowmap.network.client :as c]
   [net.bowmap.network.state :as state]
   [net.bowmap.packet-handling :as handle]
   [net.bowmap.network.message.client :as client]
   [net.bowmap.network.message.server :as server]
   [net.bowmap.server :as server-process]))

; TODO bad positional arguments, use a map?
; TODO only send in things to the server, the rest is stateful
(defn handle-packets-and-messages [client packets-in messages-in messages-out packets-out]
  (alt!!
    messages-out ([msg]
                  ; Make one of these keepalive
                  ; How does keepalive being though?
                  (assert (>!! packets-out (client/message->packet msg (::state/state client))))
                  client)
    ; These could be agents around clients with vectors as well instead of immutable maps holding channels
    ; Put this onto messages-in after translating?
    ; Check messages-out and send to uhh yeah
    ;; TODO do you need to send messages out before reading them?
    packets-in ([buf]
                (when buf
                  (when-some [msg (server/packet->message buf (::state/state client))]
                    (handle/handle-packet!! client msg))))))

; Do I need to close out?
(defn client-handler [packets-in packets-out]
  (let [messages-out (chan)
        messages-in (chan)
        client {::state/state ::state/handshaking
                ::c/messages-out messages-out}]
    ; Client is not data
    (try (loop [client client]
           (when-some [client (handle-packets-and-messages client packets-in messages-in messages-out packets-out)]
             (recur client)))
         (catch Throwable e
           ; Disconnect/cleanup?
           (println "In client handler: " e)))))

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

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

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