-
Notifications
You must be signed in to change notification settings - Fork 0
Custom Packets
mega12345mega edited this page Jan 25, 2023
·
1 revision
Create a new class, and extend Packet.
Provide the write(DataOutputStream) for serializing the packet, and a constructor or static method that inputs a DataInputStream for deserialization.
Example:
public class NamePacket extends Packet {
private final String name;
public NamePacket(DataInputStream in) throws IOException {
this.name = in.readUTF();
}
public NamePacket(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public void write(DataOutputStream out) throws IOException {
out.writeUTF(name);
}
}
The PacketRegistry allows you to register all your packets in one place, to be used later. The Client, Server, and ServerConnection also extend PacketRegistry, so you can register packets directly.
Ordering matters. The first packet registered on one side will be received as the first packet registered on the other side. If the first packet matches, then this works. If the packets are out of order, a different packet will be received than the one sent.
Example:
PacketRegistry registry = new PacketRegistry();
registry.registerPacket(NamePacket.class); // Uses NamePacket's constructor when receiving this packet
registry.registerPacket(AnotherPacket.class, AnotherPacket::fromStream); // Uses AnotherPacket.fromStream(DataInputStream)
Server server = new Server(31415);
server.registerPackets(registry); // Registers all the packets from registry
Client client = new Client(31415);
client.registerPackets(registry); // You can reuse registry in other contexts
client.registerPacket(ThirdPacket.class); // Registering directly
Client anotherClient = new Client(31415); // This client cannot effectively communicate with the server
client.registerPacket(ThirdPacket.class); // Since ThirdPacket would be received as NamePacket, due to ordering
client.registerPackets(registry);