Skip to content

Defining Your Protocol

Parker Hawke edited this page Feb 3, 2024 · 2 revisions

The most important class for Networking is MessageProtocol which allows you to declare important information such as the channel across which messages will be sent, the protocol's version, and registration of packets. This class is generically typed which requires both a serverbound and clientbound message listener type, but for this example we'll use the standard, empty listener types. Because Networking is intended to work between two platform libraries, our project structure should look something like this:

parent
| - > common (where our protocol will be defined)
| - > server (the server code, depends on common)
| - > client (the client code, depends on common)

In our common project, let's create a new class called Example which will hold the constants for our protocol, and then define these necessary constants and our empty protocol.

package com.example.project;

import wtf.choco.network.MessageProtocol;
import wtf.choco.network.data.NamespacedKey;
import wtf.choco.network.listener.ClientboundMessageListener;
import wtf.choco.network.listener.ServerboundMessageListener;

public final class Example {

    public static final NamespacedKey CHANNEL = NamespacedKey.of("example", "main");
    public static final int VERSION = 1;

    public static final MessageProtocol<ServerboundMessageListener, ClientboundMessageListener> PROTOCOL = new MessageProtocol<>(CHANNEL, VERSION,
            // These can be empty for now
            serverboundRegistry -> { },
            clientboundRegistry -> { }
    );

    private Example() { } // This will prevent anyone from constructing this class

}

That's it! You've defined your first protocol. Albeit empty and fairly useless on its own, this is all it takes to define a protocol. In the constructor we've provided 4 crucial arguments. A channel key, a protocol version, and two registry callbacks. The channel key is our unique identifier and is how Networking knows to read and write to and from this protocol on either environment. The version is arbitrary, but allows for a centralized place for you to write packets that may check for version mismatches. And lastly, the two registry callbacks are where you will register your messages once you've defined them. For now, we'll keep them empty.

Clone this wiki locally