packet.clj

Branches > main > 02e7024 > files / src / net / bowmap / network / protocol / packet.clj

(ns net.bowmap.network.protocol.packet
  (:require
   [dev.grahp.spec :as S]
   [net.bowmap.network.protocol.readers :as read])
  (:import
   [io.netty.buffer ByteBuf Unpooled]))

; The serialized form of a message, called a packet by everyone else :p
; See https://minecraft.wiki/w/Java_Edition_protocol/Packets

; TODO rename to a frame, packet is still an overloaded term
(S/def ::packet #(instance? ByteBuf %))

(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/->varint buf)
                 res' (rf res (ByteBuf/.copy (ByteBuf/.readRetainedSlice buf len)))]
             (ByteBuf/.discardReadBytes buf)
             (recur res'))
           res))))))