-
Notifications
You must be signed in to change notification settings - Fork 1
Examples
RazorPlay01 edited this page May 14, 2025
·
2 revisions
This section provides practical examples of using the Minecraft Networking API.
Create a NotificationPacket to send a message from the server to the client.
import com.github.razorplay.packet_handler.network.IPacket;
import com.github.razorplay.packet_handler.exceptions.PacketSerializationException;
import com.github.razorplay.packet_handler.network.network_util.PacketDataSerializer;
public class NotificationPacket implements IPacket {
private String message;
public NotificationPacket() {}
public NotificationPacket(String message) { this.message = message; }
@Override
public void read(PacketDataSerializer serializer) throws PacketSerializationException {
this.message = serializer.readString();
}
@Override
public void write(PacketDataSerializer serializer) throws PacketSerializationException {
serializer.writeString(message);
}
@Override
public String getPacketId() {
return "NotificationPacket";
}
public String getMessage() { return message; }
}Register and send the packet:
PacketTCP.registerPackets(NotificationPacket.class);
PacketSender.sendPacketToClient(player, new NotificationPacket("Welcome to the server!"));Handle the incoming packet:
ClientPlayNetworking.registerGlobalReceiver(FabricCustomPayload.CUSTOM_PAYLOAD_ID, (payload, context) -> {
if (payload.packet() instanceof NotificationPacket packet) {
context.client().execute(() -> {
System.out.println("Notification: " + packet.getMessage());
});
}
});A packet with a list of scores:
public class ScorePacket implements IPacket {
private Map<String, Integer> scores;
public ScorePacket() {}
public ScorePacket(Map<String, Integer> scores) { this.scores = scores; }
@Override
public void read(PacketDataSerializer serializer) throws PacketSerializationException {
this.scores = serializer.readMap(PacketDataSerializer::readString, PacketDataSerializer::readInt);
}
@Override
public void write(PacketDataSerializer serializer) throws PacketSerializationException {
serializer.writeMap(scores, PacketDataSerializer::writeString, PacketDataSerializer::writeInt);
}
@Override
public String getPacketId() {
return "ScorePacket";
}
}