Skip to content

Commit 5bb679c

Browse files
committed
Add networking documentation
1 parent eb25c17 commit 5bb679c

File tree

5 files changed

+229
-130
lines changed

5 files changed

+229
-130
lines changed
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
Using Configuration Tasks
2+
====================
3+
4+
The networking protocol for the client and server has a specific phase where the server can configure the client before the player actually joins the game.
5+
This phase is called the configuration phase, and is for example used by the vanilla server to send the resource pack information to the client.
6+
7+
This phase can also be used by mods to configure the client before the player joins the game.
8+
9+
## Registering a configuration task
10+
The first step to using the configuration phase is to register a configuration task.
11+
This can be done by registering a new configuration task in the `OnGameConfigurationEvent` event.
12+
```java
13+
@SubscribeEvent
14+
public static void register(final OnGameConfigurationEvent event) {
15+
event.register(new MyConfigurationTask());
16+
}
17+
```
18+
The `OnGameConfigurationEvent` event is fired on the mod bus, and exposes the current listener used by the server to configure the relevant client.
19+
A modder can use the exposed listener to figure out if the client is running the mod, and if so, register a configuration task.
20+
21+
## Implementing a configuration task
22+
A configuration task is a simple interface: `ICustomConfigurationTask`.
23+
This interface has two methods: `void run(Consumer<CustomPacketPayload> sender);`, and `ConfigurationTask.Type type();` which returns the type of the configuration task.
24+
The type is used to identify the configuration task.
25+
An example of a configuration task is shown below:
26+
```java
27+
public record MyConfigurationTask implements ICustomConfigurationTask {
28+
public static final ConfigurationTask.Type TYPE = new ConfigurationTask.Type(new ResourceLocation("mymod:my_task"));
29+
30+
@Override
31+
public void run(final Consumer<CustomPacketPayload> sender) {
32+
final MyData payload = new MyData();
33+
sender.accept(payload);
34+
}
35+
36+
@Override
37+
public ConfigurationTask.Type type() {
38+
return TYPE;
39+
}
40+
}
41+
```
42+
43+
## Acknowledging a configuration task
44+
Your configuration is executed on the server, and the server needs to know when the next configuration task can be executed.
45+
This is done by acknowledging the execution of said configuration task.
46+
47+
There are two primary ways of achieving this:
48+
49+
### Capturing the listener
50+
When the client does not need to acknowledge the configuration task, then the listener can be captured, and the configuration task can be acknowledged directly on the server side.
51+
```java
52+
public record MyConfigurationTask(ServerConfigurationListener listener) implements ICustomConfigurationTask {
53+
public static final ConfigurationTask.Type TYPE = new ConfigurationTask.Type(new ResourceLocation("mymod:my_task"));
54+
55+
@Override
56+
public void run(final Consumer<CustomPacketPayload> sender) {
57+
final MyData payload = new MyData();
58+
sender.accept(payload);
59+
listener.finishCurrentTask(type());
60+
}
61+
62+
@Override
63+
public ConfigurationTask.Type type() {
64+
return TYPE;
65+
}
66+
}
67+
```
68+
To use such a configuration task, the listener needs to be captured in the `OnGameConfigurationEvent` event.
69+
```java
70+
@SubscribeEvent
71+
public static void register(final OnGameConfigurationEvent event) {
72+
event.register(new MyConfigurationTask(event.listener()));
73+
}
74+
```
75+
Then the next configuration task will be executed immediately after the current configuration task has completed, and the client does not need to acknowledge the configuration task.
76+
Additionally, the server will not wait for the client to properly process the send payloads.
77+
78+
### Acknowledging the configuration task
79+
When the client needs to acknowledge the configuration task, then you will need to send your own payload to the client:
80+
```java
81+
public record AckPayload() implements CustomPacketPayload {
82+
public static final ResourceLocation ID = new ResourceLocation("mymod:ack");
83+
84+
@Override
85+
public void write(final FriendlyByteBuf buffer) {
86+
// No data to write
87+
}
88+
89+
@Override
90+
public ResourceLocation id() {
91+
return ID;
92+
}
93+
}
94+
```
95+
When a payload from a server side configuration task is properly processed you can send this payload to the server to acknowledge the configuration task.
96+
```java
97+
public void onMyData(MyData data, ConfigurationPayloadContext context) {
98+
context.submitAsync(() -> {
99+
blah(data.name());
100+
})
101+
.exceptionally(e -> {
102+
// Handle exception
103+
context.packetHandler().disconnect(Component.translatable("my_mod.configuration.failed", e.getMessage()));
104+
return null;
105+
})
106+
.thenAccept(v -> {
107+
context.replyHandler().send(new AckPayload());
108+
});
109+
}
110+
```
111+
Where `onMyData` is the handler for the payload that was sent by the server side configuration task.
112+
113+
When the server receives this payload it will acknowledge the configuration task, and the next configuration task will be executed:
114+
```java
115+
public void onAck(AckPayload payload, ConfigurationPayloadContext context) {
116+
context.taskCompletedHandler().onTaskCompleted(MyConfigurationTask.TYPE);
117+
}
118+
```
119+
Where `onAck` is the handler for the payload that was sent by the client.
120+
121+
## Stalling the login process
122+
When the configuration is not acknowledged, then the server will wait forever, and the client will never join the game.
123+
So it is important to always acknowledge the configuration task, unless the configuration task failed, then you can disconnect the client.

docs/networking/entities.md

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,14 @@ In addition to regular network messages, there are various other systems provide
66
Spawn Data
77
----------
88

9-
In general, the spawning of modded entities is handled separately, by Forge.
10-
11-
:::note
12-
This means that simply extending a vanilla entity class may not inherit all its behavior. You may need to implement certain vanilla behaviors yourself.
13-
:::
9+
Since 1.20.2 Mojang introduced the concept of Bundle packets, which are used to send entity spawn packets together.
10+
This allows for more data to be sent with the spawn packet, and for that data to be sent more efficiently.
1411

1512
You can add extra data to the spawn packet Forge sends by implementing the following interface.
1613

17-
### IEntityAdditionalSpawnData
18-
14+
### IEntityWithComplexSpawn
1915
If your entity has data that is needed on the client, but does not change over time, then it can be added to the entity spawn packet using this interface. `#writeSpawnData` and `#readSpawnData` control how the data should be encoded to/decoded from the network buffer.
16+
Alternatively you can override the method `sendPairingData(...)` which is called when the entity is paired with a client. This method is called on the server, and can be used to send additional payloads to the client within the same bundle as the spawn packet.
2017

2118
Dynamic Data
2219
------------

docs/networking/index.md

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,8 @@ There are two primary goals in network communication:
1212

1313
The most common way to accomplish these goals is to pass messages between the client and the server. These messages will usually be structured, containing data in a particular arrangement, for easy sending and receiving.
1414

15-
There are a variety of techniques provided by Forge to facilitate communication mostly built on top of [netty][].
16-
17-
The simplest, for a new mod, would be [SimpleImpl][channel], where most of the complexity of the netty system is abstracted away. It uses a message and handler style system.
15+
There is a technique provided by Forge to facilitate communication mostly built on top of [netty][].
16+
This technique can be used by listening for the `RegisterPayloadHandlerEvent` event, and then registering a specific type of [payloads][], its reader, and its handler function to the registrar.
1817

1918
[netty]: https://netty.io "Netty Website"
20-
[channel]: ./simpleimpl.md "SimpleImpl in Detail"
19+
[payloads]: ./payload.md "Registering custom Payloads"

docs/networking/payload.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
Registering Payloads
2+
====================
3+
4+
Payloads are a way to send arbitrary data between the client and the server. They are registered using the `IPayloadRegistrar` that can be retrieved for a given namespace from the `RegisterPayloadHandlerEvent` event.
5+
```java
6+
@SubscribeEvent
7+
public static void register(final RegisterPacketHandlerEvent event) {
8+
final IPayloadRegistrar registrar = event.registrar("mymod");
9+
}
10+
```
11+
12+
Assuming we want to send the following data:
13+
```java
14+
public record MyData(String name, int age) {}
15+
```
16+
17+
Then we can implement the `CustomPacketPayload` interface to create a payload that can be used to send and receive this data.
18+
```java
19+
public record MyData(String name, int age) implements CustomPacketPayload {
20+
21+
public static final ResourceLocation ID = new ResourceLocation("mymod", "my_data");
22+
23+
public MyData(final FriendlyByteBuf buffer) {
24+
this(buffer.readUtf(), buffer.readInt());
25+
}
26+
27+
@Override
28+
public void write(final FriendlyByteBuf buffer) {
29+
buffer.writeUtf(name());
30+
buffer.writeInt(age());
31+
}
32+
33+
@Override
34+
public ResourceLocation id() {
35+
return ID;
36+
}
37+
}
38+
```
39+
As you can see from the example above the `CustomPacketPayload` interface requires us to implement the `write` and `id` methods. The `write` method is responsible for writing the data to the buffer, and the `id` method is responsible for returning a unique identifier for this payload.
40+
We then also need a reader to register this later on, here we can use a custom constructor to read the data from the buffer.
41+
42+
Finally, we can register this payload with the registrar:
43+
```java
44+
@SubscribeEvent
45+
public static void register(final RegisterPacketHandlerEvent event) {
46+
final IPayloadRegistrar registrar = event.registrar("mymod");
47+
registar.play(MyData.ID, MyData::new, handler -> handler
48+
.client(ClientPayloadHandler.getInstance()::handleData)
49+
.server(ServerPayloadHandler.getInstance()::handleData));
50+
}
51+
```
52+
Dissecting the code above we can notice a couple of things:
53+
- The registrar has a `play` method, that can be used for registering payloads which are send during the play phase of the game.
54+
- Not visible in this code are the methods `configuration` and `common`, however they can also be used to register payloads for the configuration phase. The `common` method can be used to register payloads for both the configuration and play phase simultaneously.
55+
- The constructor of `MyData` is used as a method reference to create a reader for the payload.
56+
- The third argument for the registration method is a callback that can be used to register the handlers for when the payload arrives at either the client or server side.
57+
- The `client` method is used to register a handler for when the payload arrives at the client side.
58+
- The `server` method is used to register a handler for when the payload arrives at the server side.
59+
- There is additionally a secondary registration method `play` on the registrar itself that accepts a handler for both the client and server side, this can be used to register a handler for both sides at once.
60+
61+
Now that we have registered the payload we need to implement a handler.
62+
For this example we will specifically take a look at the client side handler, however the server side handler is very similar.
63+
```java
64+
public class ClientPayloadHandler {
65+
66+
private static final ClientPayloadHandler INSTANCE = new ClientPayloadHandler();
67+
68+
public static ClientPayloadHandler getInstance() {
69+
return INSTANCE;
70+
}
71+
72+
public void handleData(final MyData data, final PlayPayloadContext context) {
73+
// Do something with the data, on the network thread
74+
blah(data.name());
75+
76+
// Do something with the data, on the main thread
77+
context.workHandler().submitAsync(() -> {
78+
blah(data.age());
79+
})
80+
.exceptionally(e -> {
81+
// Handle exception
82+
context.packetHandler().disconnect(Component.translatable("my_mod.networking.failed", e.getMessage()));
83+
return null;
84+
});
85+
}
86+
}
87+
```
88+
Here a couple of things are of note:
89+
- The handling method here gets the payload, and a contextual object. The contextual object is different for the play and configuration phase, and if you register a common packet, then it will need to accept the super type of both contexts.
90+
- The handler of the payload method is invoked on the networking thread, so it is important to do all the heavy work here, instead of blocking the main game thread.
91+
- If you want to run code on the main game thread you can use the `workHandler` of the context to submit a task to the main thread.
92+
- The `workHandler` will return a `CompletableFuture` that will be completed on the main thread, and can be used to submit tasks to the main thread.
93+
- Notice: A `CompletableFuture` is returned, this means that you can chain multiple tasks together, and handle exceptions in a single place.
94+
- If you do not handle the exception in the `CompletableFuture` then it will be swallowed, **and you will not be notified of it**.
95+
96+
Now that you know how you can facilitate the communication between the client and the server for your mod, you can start implementing your own payloads.
97+
With your own payloads you can then use those to configure the client and server using [Configuration Tasks][]
98+
99+
[Configuration Tasks]: ./configuration-tasks.md

0 commit comments

Comments
 (0)