Changes

9,233 bytes added ,  07:45, 10 June 2022
Copy SimpleChannel to MC1.18 archive
SimpleChannel is the name given to the packet system that revolves around the <code><nowiki>SimpleChannel</nowiki></code> class. Using this system is by far the easiest way to send custom data between clients and the server.

== Getting Started ==

First you need to create your <code><nowiki>SimpleChannel</nowiki></code> object. We recommend that you do this in a separate class, possibly something like <code><nowiki>ModidPacketHandler</nowiki></code>. Create your <code><nowiki>SimpleChannel</nowiki></code> as a static field in this class, like so:

<syntaxhighlight lang="java">
private static final String PROTOCOL_VERSION = "1";
public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(
new ResourceLocation("mymodid", "main"),
() -> PROTOCOL_VERSION,
PROTOCOL_VERSION::equals,
PROTOCOL_VERSION::equals
);
</syntaxhighlight>

The first argument is a name for the channel. The second argument is a <code><nowiki>Supplier<String></nowiki></code> returning the current network protocol version. The third and fourth arguments respectively are <code><nowiki>Predicate<String></nowiki></code> checking whether an incoming connection protocol version is network-compatible with the client or server, respectively.
Here, we simply compare with the <code><nowiki>PROTOCOL_VERSION</nowiki></code> field directly, meaning that the client and server <code><nowiki>PROTOCOL_VERSION</nowiki></code>s must always match or FML will deny login.

== Protocol Versions ==
If your mod does not require the other side to have a specific network channel, or to be a Forge instance at all, you should take care that you properly define your version compatibility checkers (the <code><nowiki>Predicate<String></nowiki></code> parameters) to handle additional "meta-versions" (defined in <code><nowiki>NetworkRegistry</nowiki></code>) that can be received by the version checker. These are:
* <code><nowiki>ABSENT</nowiki></code> - if this channel is missing on the other endpoint. Note that in this case, the endpoint is still a Forge endpoint, and may have other mods.
* <code><nowiki>ACCEPTVANILLA</nowiki></code> - if the endpoint is a vanilla (or non-Forge) endpoint.

Returning <code><nowiki>false</nowiki></code> for both means that this channel must be present on the other endpoint. If you just copy the code above, this is what it does. Note that these values are also used during the list ping compatibility check, which is responsible for showing the green check / red cross in the multiplayer server select screen.

== Registering Packets ==

Next, we must declare the types of messages that we would like to send and receive. This is done using the <code><nowiki>INSTANCE.registerMessage</nowiki></code> method, which takes 5 parameters.

* The first parameter is the discriminator for the packet. This is a per-channel unique ID for the packet. We recommend you use a local variable to hold the ID, and then call registerMessage using <code><nowiki>id++</nowiki></code>. This will guarantee 100% unique IDs.
* The second parameter is the actual packet class <code><nowiki>MSG</nowiki></code>.
* The third parameter is a <code><nowiki>BiConsumer<MSG, FriendlyByteBuf></nowiki></code> responsible for encoding the message into the provided <code><nowiki>FriendlyByteBuf</nowiki></code>
* The fourth parameter is a <code><nowiki>Function<FriendlyByteBuf, MSG></nowiki></code> responsible for decoding the message from the provided <code><nowiki>FriendlyByteBuf</nowiki></code>
* The final parameter is a <code><nowiki>BiConsumer<MSG, Supplier<NetworkEvent.Context>></nowiki></code> responsible for handling the message itself

The last three parameters can be method references to either static or instance methods in Java. Remember that an instance method <code><nowiki>MSG.encode(FriendlyByteBuf)</nowiki></code> still satisfies <code><nowiki>BiConsumer<MSG, FriendlyByteBuf></nowiki></code>, the <code><nowiki>MSG</nowiki></code> simply becomes the implicit first argument.

<syntaxhighlight lang="java">
// A class MessagePacket
public void encoder(FriendlyByteBuf buffer) {
// Write to buffer
}

public static MessagePacket decoder(FriendlyByteBuf buffer) {
// Create packet from buffer data
}

public void messageConsumer(Supplier<NetworkEvent.Context>> ctx) {
// Handle message
}

// For some SimpleChannel channel
channel.registerMessage(id, MessagePacket::encoder, MessagePacket::decoder, MessagePacket::messageConsumer);
</syntaxhighlight>

== Handling Packets ==

There are a couple things to highlight in a packet handler. A packet handler has both the message object and the network context available to it. The context allows access to the player that sent the packet (if on the server), and a way to enqueue threadsafe work.

<syntaxhighlight lang="java">
public static void handle(MyMessage msg, Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
// Work that needs to be threadsafe (most work)
ServerPlayer sender = ctx.get().getSender(); // the client that sent this packet
// do stuff
});
ctx.get().setPacketHandled(true);
}
</syntaxhighlight>

Packets sent from the server to the client should be handled in another class and wrapped via <code>DistExecutor#unsafeRunWhenOn</code>.

<syntaxhighlight lang="java">
// In Packet class
public static void handle(MyClientMessage msg, Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() ->
// Make sure it's only executed on the physical client
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> ClientPacketHandlerClass.handlePacket(msg, ctx))
);
ctx.get().setPacketHandled(true);
}

// In ClientPacketHandlerClass
public static void handlePacket(MyClientMessage msg, Supplier<NetworkEvent.Context> ctx) {
// Do stuff
}
</syntaxhighlight>

Note the presence of <code><nowiki>#setPacketHandled</nowiki></code>, which used to tell the network system that the packet has successfully completed handling.

=== Common Packet Handling Pitfalls ===

{{Colored box|title=Know that packets are by default handled on the network thread.|content=
That means that your handler can ''not'' interact with most game objects directly.
Forge provides a convenient way to make your code execute on the main thread through the supplied <code><nowiki>NetworkEvent$Context</nowiki></code>.
Simply call <code><nowiki>NetworkEvent$Context#enqueueWork(Runnable)</nowiki></code>, which will call the given <code><nowiki>Runnable</nowiki></code> on the main thread at the next opportunity.}}

{{Colored box|title=Be defensive when handling packets on the server.|content=
A client could attempt to exploit the packet handling by sending unexpected data.
<br>
A common problem is vulnerability to <code>arbitrary chunk generation</code>. This typically happens when the server is trusting a block position sent by a client to access blocks and block entities. When accessing blocks and block entities in unloaded areas of the level, the server will either generate or load this area from disk, then promply write it to disk. This can be exploited to cause <code>catastrophic damage</code> to a server's performance and storage space without leaving a trace.
<br>
To avoid this problem, a general rule of thumb is to only access blocks and block entities if <code><nowiki>Level#hasChunkAt</nowiki></code> is true.}}

{{Colored box|title=Register encoders on the physical client, as well as the physical server.|content=
If you only register an encoder for a clientbound packet on the physical server, your mod will likely crash or present unintended behaviour in single-player worlds. ''Forge will happily send packets that have no encoder defined, '''without a warning or error message!''''' They will be encoded as a 256-long byte buffer filled only with null bytes, by default.
<br>}}

== Sending Packets ==

=== Sending to the Server ===

There is but one way to send a packet to the server. This is because there is only ever *one* server the client can be connected to at once. To do so, we must again use that <code><nowiki>SimpleChannel</nowiki></code> that was defined earlier. Simply call <code><nowiki>INSTANCE.sendToServer(new MyMessage())</nowiki></code>. The message will be sent to the handler for its type, if one exists.

=== Sending to Clients ===

Packets can be sent directly to a client using the <code><nowiki>SimpleChannel</nowiki></code>: <code><nowiki>HANDLER.sendTo(MSG, serverPlayer.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT)</nowiki></code>. However, this can be quite inconvenient. Forge has some convenience functions that can be used:

<syntaxhighlight lang="java">
// Sending to one player
INSTANCE.send(PacketDistributor.PLAYER.with(serverPlayer), new MyMessage());

// Send to all players tracking this level chunk
INSTANCE.send(PacketDistributor.TRACKING_CHUNK.with(levelChunk), new MyMessage());

// Sending to all connected players
INSTANCE.send(PacketDistributor.ALL.noArg(), new MyMessage());
</syntaxhighlight>

There are additional <code><nowiki>PacketDistributor</nowiki></code> types available, check the documentation on the <code><nowiki>PacketDistributor</nowiki></code> class for more details.
372

edits