tinycodinglm / mc /mc-0040.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame Contribute Delete
2.65 kB
opencode trace
System You are an expert Fabric mod developer. You write idiomatic Minecraft Fabric mods using Java, Fabric API, and Yarn mappings.

You are an expert Fabric mod developer. You write idiomatic Minecraft Fabric mods using Java, Fabric API, and Yarn mappings.

User

How do I create custom networking packets between client and server in Fabric?

Assistant
java
package com.example.mymod.networking;

import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.util.Identifier;

public class MyNetworking {
    public static final CustomPayload.Id<ExamplePayload> EXAMPLE_ID = 
        new CustomPayload.Id<>(Identifier.of("mymod", "example"));

    public record ExamplePayload(String message, int value) implements CustomPayload {
        public static final PacketCodec<PacketByteBuf, ExamplePayload> CODEC = 
            PacketCodec.of(
                buf -> new ExamplePayload(buf.readString(), buf.readInt()),
                (buf, payload) -> { buf.writeString(payload.message()); buf.writeInt(payload.value()); }
            );
        @Override
        public Id<? extends CustomPayload> getId() { return EXAMPLE_ID; }
    }

    public static void register() {
        PayloadTypeRegistry.playC2S().register(EXAMPLE_ID, ExamplePayload.CODEC);
        PayloadTypeRegistry.playS2C().register(EXAMPLE_ID, ExamplePayload.CODEC);

        ServerPlayNetworking.registerGlobalReceiver(EXAMPLE_ID, (payload, context) -> {
            context.server().execute(() -> {
                context.player().sendMessage(
                    Text.literal("Server received: " + payload.message() + " - " + payload.value()));
            });
        });

        ClientPlayNetworking.registerGlobalReceiver(EXAMPLE_ID, (payload, context) -> {
            context.client().execute(() -> {
                context.client().player.sendMessage(
                    Text.literal("Client received: " + payload.message()));
            });
        });
    }
}

Sending packets:

java
ClientPlayNetworking.send(new MyNetworking.ExamplePayload("Hello", 42));
ServerPlayNetworking.send(player, new MyNetworking.ExamplePayload("Response", 100));