NetworkMessage

Network Message Protocol

DOTSNET comes with its own message protocol. While you will never have to worry about it, it is good to know when debugging or designing external applications.

  • Client->Server Messages: <<messageId:ushort, message:bytes>>

  • Server->Client Messages: <<messageId:ushort, amount:uint, messages:bytes>>

NetworkMessage Interface

All messages need to be structs that implement the NetworkMessage interface.

Function:

Description:

Serialize(NetworkWriter)

Serializes message contents into writer.

Deserialize(NetworkReader)

Deserializes message contents from reader.

Sending a NetworkMessage

NetworkServerSystem.Send can send a NetworkMessage to a client connection.

NetworkClientSystem.Send can send a NetworkMessage to the server.

Whenever we want to send something from the client to the server, or from the server to a client, we need to use a NetworkMessage.

Simply create a struct that implements the NetworkMessage interface and add the serialize & deserialize methods:

using DOTSNET;

public struct JoinWorldMessage : NetworkMessage
{
    public Bytes16 playerPrefabId;
    
    public bool Serialize(ref NetworkWriter writer) =>
        writer.WriteBytes16(playerPrefabId);

    public bool Deserialize(ref NetworkReader reader) =>
        reader.ReadBytes16(out playerPrefabId);
}

Message IDs are automatically generated from the message's type name hash.

Receiving a NetworkMessage

Inherit from NetworkServerMessageSystem to handle a received message on the server:

using DOTSNET;

public class JoinWorldMessageSystem : NetworkServerMessageSystem<JoinWorldMessage>
{
    protected override bool RequiresAuthentication() => true;
    protected override void OnMessage(int connectionId, JoinWorldMessage message)
    {
        // handle the message
    }
}

Almost all server messages should require authentication. For example, a client that hasn’t logged in shouldn’t be able to send a player movement message.

Inherit from NetworkClientMessageSystem to handle a received message on the client:

using DOTSNET;

public class MyMessageSystem : NetworkClientMessageSystem<MyMessage>
{
    protected override void OnMessage(MyMessage message)
    {
        // handle the message
    }
}

Last updated