BKCommonLib/Packets

From BergerHealer Wiki
Revision as of 20:55, 9 June 2021 by RyanDo (talk | contribs) (Created page with "« Go back ==Introduction== To keep keep track of packets being sent between the server and the client, BKCommonLib provides a packet listener to intercept an...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

« Go back

Introduction

To keep keep track of packets being sent between the server and the client, BKCommonLib provides a packet listener to intercept and handle these packets. When ProtocolLib is found, this plugin is used to provide the listening, otherwise a hacky workaround is used. We recommend you install ProtocolLib as well for that reason.

Usage

How to register a packet listener and how to read and change the packets.

Registering

Use the following method to register your PacketListener implementing class:

PacketUtil.addPacketListener(plugin, myPacketListener, PacketType.OUT_CHAT);

To create a Packet listener class for your plugin, create a new Class that implements PacketListener, and override the onPacketReceive and onPacketSend methods. There are INcoming and OUTgoing Packet Types, they register for the methods respectively.

Working with packets

Packets change all the time, so it was not possible to include a wrapper class for each and every packet. To work with packets, BKCommonLib provides you a reflection-based system for accessing fields and constructing new packets, namely PacketType:

@Override
public void onPacketSend(PacketSendEvent event) {
    CommonPacket packet = event.getPacket();
    if (packet.getType() == PacketType.OUT_CHAT) {
        String oldMessage = packet.read(PacketType.OUT_CHAT.message);
        if (oldMessage.contains("curse")) {
            packet.write(PacketType.OUT_CHAT.message, oldMessage.replace("curse", "curse is awesome"));
        }
    }
}

There are also methods to read/write a certain parameter index or by name, but they are generally unsafe. We recommend you use the PacketFields constants for this instead, so your plugin remains compatible when fields change. For example, if the 'message' String field is replaced with a List of Strings, we can still provide you with a (deprecated) message field which sets that other field.