Skip to content

Packet listeners and adapters

Dan Mulloy edited this page Jul 2, 2021 · 7 revisions

Plugins can listen for packets through PacketAdapters. A packet adapter is generally set up like this:

ProtocolManager manager = ProtocolLibrary.getProtocolManager();
manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Client.CHAT) {
    @Override
    public void onPacketReceiving(PacketEvent event) {
        Player player = event.getPlayer();
        PacketContainer packet = event.getPacket();
        if (isMuted(player)) {
            System.out.println("[MUTED] " + player.getName() + ": " + packet.getStrings().read(0));
            event.setCancelled(true);
        }
    }
});

This is a rather trivial example to listen for incoming chat packets and block them if a player is muted. There are a few things to unpack though:

PacketType

PacketType is an enum-like class that contains every packet supported by ProtocolLib. PacketTypes are formatted as PacketType.[Game Phase].[Direction].[Packet Name]. The game phase is one of Handshake, Play (you'll probably mostly be working with play), Status, and Login. The direction is either Client (incoming packets) or Server (outgoing packets)

You can find a list of all packets in the JavaDocs. Note that @Deprecated packets may be supported on older Minecraft versions, but not the latest.

PacketContainer

PacketContainer is how plugins can modify packets with ProtocolLib. It contains accessors for every type of field present in Minecraft packets. In this example, packet.getStrings() returns a modifier for each String field in the chat packet.

You can read more about PacketContainers on the wiki page: PacketContainer

Odds and Ends

  • Every packet can be cancelled with event.setCancelled(true) (that doesn't mean you should, but you can)
  • In some game phases (non-play ones), event.getPlayer() will sometimes return a TemporaryPlayer when a Bukkit player is not available. They have a reduced set of available methods and can be checked for with event.isPlayerTemporary()

That's all for now

Feel free to contribute pages and/or content, though! I'll be working on adding more as I have the time.

Clone this wiki locally