Communicating with a server

Information

LabyMod provides an API which allows you to communicate with a Minecraft server by sending and receiving simple JSON messages. Every message sent through the API is identified by a key which can be selected freely by the developer. It is necessary to properly distinguish messages from each other, so make sure to use a meaningful name. The recommended way of naming keys is a combination of your addon/plugin name and a custom key separated by a dash (-). That way we can eliminte duplicates and therefore, errors.
Examples: "TimoliaAddon-FriendJoin", "WorldEditCUI-GenerateSphere"

Note

If you want to know how to send messages from the server to the client, visit this page.

Handling incoming messages

Handling a server's messages is quite simple. You just have to register a listener by using LabyModAddon#getApi()#getEventManager()#register( ServerMessageEvent listener ) (see LabyMod events)

Example (which refers to this example):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
myAddon.getApi().getEventManager().register( new ServerMessageEvent() {

    /**
     * Called when an API-message was sent by the server
     *
     * @param messageKey    the message-key you can identify the message's content by
     * @param serverMessage the message (a json element)
     */
    public void onServerMessage( String messageKey, JsonElement serverMessage ) {
        // Checking whether the message is intended to update the points and whether the JSON message is a JSON object
        if( messageKey.equals( "EXAMPLE-Points" ) && serverMessage.isJsonObject() ) {
            JsonObject pointsObject = serverMessage.getAsJsonObject();

            // Checking whether a points attribute is included
            if( pointsObject.has( "points" ) ) {
                // Getting the value of the points attribute
                int points = pointsObject.get( "points" ).getAsInt();

                // Setting the points
                myAddon.setPoints( points );

                // Printing a log message
                System.out.println( "You have got " + points + " points now!" );
            }
        }
    }

} );

Sending messages to the server

You can send JSON messages to the server by using the method LabyModAddon#getApi()#sendJsonMessageToServer( String messageKey, JsonElement message ).

Example (click here to see how to handle this message):

1
2
3
4
JsonObject optionsObject = new JsonObject();
optionsObject.addProperty( "randomOption", true );

myAddon.getApi().sendJsonMessageToServer( "EXAMPLE-Options", optionsObject );