server.clj

Branches > main > 93fc876 > files / src / net / bowmap / transport / server.clj

(ns net.bowmap.transport.server
  (:require
   [clojure.core.async :refer [io-thread]]
   [net.bowmap.transport.connection :as connection])
  (:import
   [java.net ServerSocket SocketException]))

(defn accept-connection!!
  "Blocks and returns the next connection to the server.
   Returns nil if the server has closed."
  [server-socket]
  (when-let [socket (try (ServerSocket/.accept server-socket)
                         (catch SocketException _))]
    (connection/connection socket)))

(defn minecraft-server
  "Returns a function of a handler that will start a Minecraft server at the specified port.
   Connected clients will be passed asynchronously to the handler"
  [& {:keys [port]}]
  (fn [handler]
    (let [server-socket (ServerSocket. port)]
      (loop []
        (when-some [connection (accept-connection!! server-socket)]
          (io-thread (handler connection))
          (recur))))))