Changes

7,539 bytes added ,  20:42, 24 October 2020
Inital Import dokuwiki
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, PacketBuffer></nowiki></code> responsible for encoding the message into the provided <code><nowiki>PacketBuffer</nowiki></code>
* The fourth parameter is a <code><nowiki>Function<PacketBuffer, MSG></nowiki></code> responsible for decoding the message from the provided <code><nowiki>PacketBuffer</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(PacketBuffer)</nowiki></code> still satisfies <code><nowiki>BiConsumer<MSG, PacketBuffer></nowiki></code>, the <code><nowiki>MSG</nowiki></code> simply becomes the implicit first argument.

== 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)
EntityPlayerMP sender = ctx.get().getSender(); // the client that sent this packet
// do stuff
});
ctx.get().setPacketHandled(true);
}
</syntaxhighlight>

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

{{Colored box|title=Alert|content=Packets are by default handled on the network thread.
<br><br>
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 instead using <code><nowiki>IThreadListener.addScheduledTask</nowiki></code>.
Simply call <code><nowiki>ctx.get().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=Alert|content=Be defensive when handling packets on the server. A client could attempt to exploit the packet handling by sending unexpected data.
<br><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 tile entities. When accessing blocks and tile entities in unloaded areas of the world, 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 tile entities if <code><nowiki>world.isBlockLoaded(pos)</nowiki></code> is true.}}


== 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, entityPlayerMP.connection.getNetworkManager(), 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(playerMP), new MyMessage());

// Send to all players tracking this chunk
INSTANCE.send(PacketDistributor.TRACKING_CHUNK.with(chunk), 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.