Sponge.Protocol - Year4000/Utilities GitHub Wiki
This protocol system allows for developers to send packets to the set of players. But also has the ability to intercept packets that are send from and to the server.
Get the service
Packets uses Sponge's Service Manager to provide a simple interface to interact with.
Note - The all services from Utilities
are registered during GamePreInitializationEvent
.
Packets packets = Sponge.getServiceManager()
.provide(Packets.class)
.orElseThrow(RuntimeException::new);
Sending a Packet
Sending a packet is very simple, You only need to know the packet type (found on wiki.vg).
Our Packet class is a surrogate for the real packet class.
You will need to know the order of the fields to call the injector()
builder.
More info can be found on the Packets and PacketTypes.
Note - Most packets follow the schema on wiki.vg but not allways.
The following snippet will send a keep alive packet to the client.
Player player = ...;
Packet packet = new Packet(PacketTypes.PLAY_CLIENT_KEEP_ALIVE);
// note that the player's hashcode is the entity id
int entityId = player.hashCode();
packet.injector().add(entityId).inject();
packets.sendPacket(player, packet);
// Same as above but one liner
packets.sendPacket(player, new Packet(PacketTypes.PLAY_CLIENT_KEEP_ALIVE)
.injector()
.add(player.hashCode())
.inject());
Intercepting a packet
Packets are registered using a PacketListener that is a functional interface.
The PacketListener
extends a BiFunction<Player, Packet, Boolean>
.
Packets can be ignored or canceled based on the return boolean
.
PacketListener.CANCEL; // true
PacketListener.IGNORE; // false
The following snippet will intercept the packets sent to the server.
PacketType type = PacketTypes.PLAY_SERVER_KEEP_ALIVE;
packets.registerListener(type, (player, packet) -> {
// Client sent keep alive packet to server
return PacketListener.IGNORE;
});