Skip to content

Networking

Gugas749 edited this page Nov 5, 2026 · 1 revision

Networking

Each mod gets one channel, and packets are plain records. The same code works on both loaders: behind the API is a SimpleChannel on Forge and CustomPacketPayloads on NeoForge.

Step 1 — define packets

A packet is a record plus a static AbyssPacketCodec. The decoder must read fields in the same order the encoder wrote them.

import com.gugas749.abysscore.api.network.AbyssPacketCodec;

/** Server → client: "your mana is now X / Y". */
public record ManaSyncPacket(int current, int max) {
    public static final AbyssPacketCodec<ManaSyncPacket> CODEC = AbyssPacketCodec.of(
            (buf, pkt) -> {
                buf.writeVarInt(pkt.current());
                buf.writeVarInt(pkt.max());
            },
            buf -> new ManaSyncPacket(buf.readVarInt(), buf.readVarInt()));
}

/** Client → server: "cast spell #id at this block". */
public record CastSpellPacket(int spellId, BlockPos target) {
    public static final AbyssPacketCodec<CastSpellPacket> CODEC = AbyssPacketCodec.of(
            (buf, pkt) -> {
                buf.writeVarInt(pkt.spellId());
                buf.writeBlockPos(pkt.target());
            },
            buf -> new CastSpellPacket(buf.readVarInt(), buf.readBlockPos()));
}

/** A packet with no fields: AbyssPacketCodec.unit(...) writes nothing and always returns the same instance. */
public record OpenSpellbookPacket() {
    public static final OpenSpellbookPacket INSTANCE = new OpenSpellbookPacket();
    public static final AbyssPacketCodec<OpenSpellbookPacket> CODEC = AbyssPacketCodec.unit(INSTANCE);
}

Useful FriendlyByteBuf methods that exist on both 1.20.1 and 1.21.1: writeVarInt/readVarInt, writeInt/readInt, writeFloat/readFloat, writeDouble/readDouble, writeBoolean/readBoolean, writeUtf/readUtf, writeUUID/readUUID, writeEnum/readEnum(Class), writeBlockPos/readBlockPos, writeResourceLocation/readResourceLocation, writeNbt/readNbt.

Lists, written by hand so the code is the same on both versions:

public record PlayerListPacket(List<UUID> players) {
    public static final AbyssPacketCodec<PlayerListPacket> CODEC = AbyssPacketCodec.of(
            (buf, pkt) -> {
                buf.writeVarInt(pkt.players().size());
                for (UUID id : pkt.players()) buf.writeUUID(id);
            },
            buf -> {
                int size = buf.readVarInt();
                List<UUID> list = new ArrayList<>(size);
                for (int i = 0; i < size; i++) list.add(buf.readUUID());
                return new PlayerListPacket(list);
            });
}

Step 2 — create the channel and register packets

import com.gugas749.abysscore.api.network.AbyssChannel;
import com.gugas749.abysscore.api.network.AbyssNetworking;
import com.gugas749.abysscore.api.network.AbyssPacketRegistrar;

public final class MyPackets {

    /** Client and server must match. Bump it whenever any packet changes. */
    public static final String VERSION = "1";

    public static final AbyssChannel CHANNEL =
            AbyssNetworking.createChannel("mymod", VERSION, MyPackets::register);

    /** Call from your mod constructor: loading the class creates CHANNEL. */
    public static void init() {}

    private static void register(AbyssPacketRegistrar r) {
        // S2C: the handler is a Supplier, so it's only resolved on the client
        r.s2c("mana_sync",      ManaSyncPacket.class,      ManaSyncPacket.CODEC,      () -> MyClientHandlers::onManaSync);
        r.s2c("open_spellbook", OpenSpellbookPacket.class, OpenSpellbookPacket.CODEC, () -> MyClientHandlers::onOpenSpellbook);

        // C2S
        r.c2s("cast_spell",     CastSpellPacket.class,     CastSpellPacket.CODEC,     MyServerHandlers::onCastSpell);

        // NEW PACKETS GO HERE, AT THE END
    }
}
// NeoForge mod constructor
public MyMod(IEventBus modBus) {
    MyPackets.init();
}

// Forge 1.20.1 mod constructor
public MyMod() {
    MyPackets.init();
}
createChannel overload Use
createChannel(modId, version, register) The usual one. Channel name is "main".
createChannel(modId, channelName, version, register) A mod that needs more than one channel. On Forge each becomes modid:channelName. On NeoForge only the packet names are used, so packet names must be unique across all of a mod's channels.

name (the first s2c/c2s argument) becomes the packet id modid:name on NeoForge. Forge ignores it and uses the registration order.

Step 3 — handlers

A handler is (packet, AbyssPacketContext ctx) -> void.

AbyssPacketContext
enqueueWork(Runnable) Run on the main game thread. Always do your work in here.
player() C2S: the sender (a ServerPlayer, so cast it). S2C: the local client player.

Server handler: validate everything, because the client can send anything.

public final class MyServerHandlers {
    public static void onCastSpell(CastSpellPacket pkt, AbyssPacketContext ctx) {
        ctx.enqueueWork(() -> {
            if (!(ctx.player() instanceof ServerPlayer player)) return;

            // never trust the client: range, ids, permissions...
            if (pkt.spellId() < 0 || pkt.spellId() >= Spells.COUNT) return;
            if (player.blockPosition().distSqr(pkt.target()) > 64 * 64) return;
            if (Spells.isStaffOnly(pkt.spellId())
                    && !AbyssPermissionHandler.require(player, AbyssPermissionLevel.MODERATOR)) return;

            Spells.cast(player, pkt.spellId(), pkt.target());
        });
    }
}

Client handler: keep it in its own class, which is only ever referenced from the Supplier.

public final class MyClientHandlers {
    public static int clientMana, clientMaxMana;

    public static void onManaSync(ManaSyncPacket pkt, AbyssPacketContext ctx) {
        ctx.enqueueWork(() -> {
            clientMana = pkt.current();
            clientMaxMana = pkt.max();
        });
    }

    public static void onOpenSpellbook(OpenSpellbookPacket pkt, AbyssPacketContext ctx) {
        ctx.enqueueWork(() -> Minecraft.getInstance().setScreen(new SpellbookScreen()));
    }
}

Step 4 — send

// Server → one player
MyPackets.CHANNEL.sendToPlayer(serverPlayer, new ManaSyncPacket(50, 100));

// Server → every online player
MyPackets.CHANNEL.sendToAll(new WeatherEventPacket(...));

// Server → everyone who can see this entity (NOT the entity itself)
MyPackets.CHANNEL.sendToTracking(bossEntity, new BossPhasePacket(2));

// Server → everyone who can see this entity AND the entity itself, if it's a player
MyPackets.CHANNEL.sendToTrackingAndSelf(player, new AuraPacket(player.getUUID(), true));

// Client → server
MyPackets.CHANNEL.sendToServer(new CastSpellPacket(3, hitPos));

Networking checklist

  • Channel is a static final field and its class is loaded from the mod constructor
  • New packets are added at the end
  • Version string bumped after changing any packet
  • Every handler body is inside ctx.enqueueWork
  • C2S handlers cast ctx.player() to ServerPlayer and validate everything
  • S2C handlers live in a client-only class, referenced only through () -> Class::method

Clone this wiki locally