Packet listening - Exceptionflug/protocolize GitHub Wiki
In this page, you will learn how to listen for incoming and outgoing packets using AbstractPacketListener
s.
At first we need to understand how data flows between client, server and proxy.
Since Protocolize runs on the proxy server, this figure shows the data flow in the view of the proxy. Everything coming in and going out to the client is known as upstream. Everything coming in and going out to the backing minecraft server is known as downstream.
NOTICE: This example is written for the BungeeCord platform and uses the BungeeCord Chat
packet. On velocity, the packet name may differ.
In this example I will show you how to intercept chat message packets. First we need to create a new AbstractPacketListener
for that packet type.
MyPacketListener.java:
public class MyPacketListener extends AbstractPacketListener<Chat> {
public MyPacketListener() {
super(Chat.class, Direction.UPSTREAM, 0);
}
}
The super constructor needs three parameters. The type of packet to listen for, the direction and the listener priority (default is 0
). Now we are able to implement the two methods packetReceive
and packetSend
.
@Override
public void packetReceive(PacketReceiveEvent<Chat> event) {
// Receive on UPSTREAM means receiving a packet from a player
// Receive on DOWNSTREAM means receiving a packet from a server a player is connected to
}
@Override
public void packetSend(PacketSendEvent<Chat> event) {
// Sending on UPSTREAM means sending a packet to a player
// Sending on DOWNSTREAM means sending a packet to a server a player is connected with
}
For example if we want all actionbar messages printing in the chat instead we can use the following logic on Direction.DOWNSTREAM
:
public class MyPacketListener extends AbstractPacketListener<Chat> {
public MyPacketListener() {
super(Chat.class, Direction.DOWNSTREAM, 0);
}
@Override
public void packetReceive(PacketReceiveEvent<Chat> event) {
Chat packet = event.packet();
if(packet.getPosition() == 2) { // Position 2 means actionbar
packet.setPosition((byte) 0); // Set to normal chat
event.markForRewrite(); // We need to mark the packet for rewriting after we changed fields in the packet class. This is only necessary when receiving packets on BungeeCord.
}
}
}
One thing left to do. Let's register our created AbstractPacketListener
:
Protocolize.listenerProvider().registerListener(new MyPacketAdapter());