server.clj

Branches > namespace-reorganization > f2c44a9 > files / src / net / bowmap / network / server.clj

(ns net.bowmap.network.server
  (:require
   [aleph.tcp :as tcp]
   [clojure.core.async :refer [chan io-thread]]
   [manifold.stream :as s]
   [net.bowmap.instance :as instance]
   [net.bowmap.network.packet.read :as read :refer [->varint]])
  (: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 (->varint buf)
                 res' (rf res (ByteBuf/.copy (ByteBuf/.readRetainedSlice buf len)))]
             (ByteBuf/.discardReadBytes buf)
             (recur res'))
           res))))))

(defn- handle-client [stream info]
  (let [packets-in (chan 1 packet-framer-xf)
        packets-out (chan)
        client (instance/client)]
    (s/connect stream packets-in)
    (s/connect packets-out stream)
    (instance/connect! client packets-in packets-out)))

; Could return a channel of clients?
; Make sure this is just kept an interface, it really only needs to know about packets-in, packets-out, and then maybe how to close/disconnect?
(defn start-server!
  ;"Starts a server at the port, calling 'handler' with an 'in' and 'out' channel of packets."
  [& {:keys [port]}]
  (tcp/start-server handle-client
                    {:port port
                     :bootstrap-transform #(ServerBootstrap/.childOption % ChannelOption/TCP_NODELAY true)}))