server.clj
Branches > client-handling-rewrite > 16276c5 > 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.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 [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-server!
"Starts a server at the port, calling 'handler' with an 'in' and 'out' channel of packets."
[& {:keys [handler port]}]
(tcp/start-server (fn [stream info]
(handle-client handler stream info))
{:port port
:bootstrap-transform #(ServerBootstrap/.childOption % ChannelOption/TCP_NODELAY true)}))