Skip to content

Packet listening

Nico edited this page Oct 5, 2020 · 2 revisions

In this page, you will learn how to listen for incoming and outgoing packets using PacketListeners.

Introduction

At first we need to understand how data flows between client, server and proxy. This is a very sexy graphical explanation how data flows 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.

Creating a PacketListener

In this example I will show you how to intercept chat message packets. First we need to create a new PacketListener for that packet type using PacketAdapter.

MyPacketAdapter.java:

public class MyPacketAdapter extends PacketAdapter<Chat> {  
  public MyPacketListener() {  
    super(Stream.UPSTREAM, Chat.class);  
  }
}

The super constructor needs at least two parameters. The stream and the type of packet to listen for. Now we are able to override the two methods receive and send.

@Override  
public void receive(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 send(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 Stream.DOWNSTREAM:

public class MyPacketListener extends PacketAdapter<Chat> {  
 
  public MyPacketListener() {  
    super(Stream.DOWNSTREAM, Chat.class);  
  }  
 
  @Override  
  public void receive(PacketReceiveEvent<Chat> event) {  
    Chat packet = event.getPacket();  
    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. 
    }  
  }  
}

One thing left to do. Let's register our created PacketListener:

ProtocolAPI.getEventManager().registerListener(new MyPacketAdapter());
Clone this wiki locally