Class CachedPacket<T extends ToClientPacket>

java.lang.Object
com.hypixel.hytale.protocol.CachedPacket<T>
All Implemented Interfaces:
Packet, ToClientPacket, AutoCloseable

public final class CachedPacket<T extends ToClientPacket> extends Object implements ToClientPacket, AutoCloseable
A pre-serialized packet for efficient broadcast to multiple recipients. Caches the serialized bytes once, then writes them directly for each send.

Implements AutoCloseable for use with try-with-resources to prevent leaks:

  try (var cached = CachedPacket.cache(myPacket)) {
      for (var player : players) {
          player.getPacketHandler().write(cached);
      }
  } // automatically released
  • Method Details

    • cache

      public static <T extends ToClientPacket> CachedPacket<T> cache(@Nonnull T packet)
      Create a cached version of the given packet. The packet is serialized immediately and the bytes are retained.
    • getId

      public int getId()
      Description copied from interface: Packet
      Returns the unique packet ID.
      Specified by:
      getId in interface Packet
    • getChannel

      public NetworkChannel getChannel()
      Description copied from interface: Packet
      Returns the channel this packet should be sent on.
      Specified by:
      getChannel in interface Packet
    • serialize

      public int serialize(@Nonnull MemorySegment buffer, int offset)
      Description copied from interface: Packet
      Writes this packet at offset and returns the number of bytes written, which callers rely on being exactly Packet.computeSize(). The framed write path reserves and length-prefixes on that figure before serializing, so a shorter or longer write corrupts the frame rather than failing.
      Specified by:
      serialize in interface Packet
    • computeSize

      public int computeSize()
      Description copied from interface: Packet
      Compute the exact number of bytes needed to serialize this packet.
      Specified by:
      computeSize in interface Packet
    • getPacketType

      public Class<T> getPacketType()
    • getCachedSize

      public int getCachedSize()
    • close

      public void close()
      Release the underlying buffer. Call when the cached packet is no longer needed. Can also use try-with-resources for automatic cleanup.
      Specified by:
      close in interface AutoCloseable