server.clj

Branches > client-handling-rewrite > d4fb123 > files / src / net / bowmap / server.clj

(ns net.bowmap.server
  (:require
   [aleph.tcp :as tcp]
   [clojure.core.async :refer [chan io-thread]]
   [manifold.stream :as s]
   [net.bowmap.packet.read :as read])
  (:import
   [io.netty.bootstrap ServerBootstrap]
   [io.netty.buffer ByteBuf Unpooled]
   [io.netty.channel ChannelOption]))

(defn packet-framer-xf
  "Transducer that frames bytes from incoming byte arrays and outputs ByteBufs of
   framed serialized serverbound packets."
  [rf]
  (let [buf (Unpooled/buffer)]
    (fn
      ([] (rf))
      ([res] (rf res))
      ([res input]
       (ByteBuf/.writeBytes buf input)
       (loop [res res]
         (if (read/can-read-packet? buf)
           (let [len (read/read-varint! buf)
                 res' (rf res (ByteBuf/.copy (ByteBuf/.readRetainedSlice buf len)))]
             (ByteBuf/.discardReadBytes buf)
             (recur res'))
           res))))))

(defn- handle-client [handler stream info]
  (let [in (chan 1 packet-framer-xf)
        out (chan)]
    (s/connect stream in)
    (s/connect out stream)
    (io-thread (handler in out))))

; Could return a channel of clients?
(defn start-server2!
  [& {:keys [handler port]}]
  (tcp/start-server (fn [stream info]
                      (handle-client handler stream info))
                    {:port port
                     :bootstrap-transform #(ServerBootstrap/.childOption % ChannelOption/TCP_NODELAY true)}))