Skip to content

Custom Packets

Ian edited this page Aug 22, 2019 · 22 revisions

Creating your own packet type is easy, but to make it even easier i would simply copy and paste one of the pre-existing packets, and modify it to your own.

First, here are some simple rules about creating a packet:

  • A packet must inherit Packet
  • A packet must have a constructor, taking in a string and passing it to base.

Here is the definition for the TestPacket:

public class TestPacket : Packet<TestPacket>
{
    public string testString;

    public TestPacket(string packet_name) : base(packet_name){}

    public override TestPacket OpenPacketFromMessage(NetIncomingMessage msg)
    {
        TestPacket packet = new TestPacket(packet_identifier);       
        packet.testString = msg.ReadString();      

        return packet;
    }

    public override NetOutgoingMessage PackPacketIntoMessage(NetOutgoingMessage msg,  TestPacket packet)
    {
        msg.Write(packet.testString);
        return msg;
    }
       
}

'OpenPacketFromMessage' is called when the packet is received. This expects a returned packet, with the information from the message. For each thing that is written to the packet in the 'PackPacketIntoMessage' method, 'OpenPacketFromMessage' expects you to read each field to a packet object.

'PackPacketIntoMessage' is called before a packet is packaged and sent. It requires you to write each field to the message, and return said message.

Let's create a custom packet, which can store an int, a string and a float.

public class IntStringFloat : Packet<IntStringFloat>
{
    public int testInt;
    public string testString;
    public float testFloat;

    public IntStringFloat (string packet_name) : base(packet_name){}

    public override IntStringFloat OpenPacketFromMessage(NetIncomingMessage msg)
    {
        IntStringFloat packet = new IntStringFloat(packet_identifier);
     
        packet.testInt = msg.ReadInt32();
        packet.testString = msg.ReadString();
        packet.testFloat = msg.ReadFloat();      

        return packet;
    }

    public override NetOutgoingMessage PackPacketIntoMessage(NetOutgoingMessage msg,  IntStringFloat packet)
    {
        msg.Write(packet.testInt);
        msg.Write(packet.testString);
        msg.Write(packet.testFloat);

        return msg;
    }
       
}

With a connected client, we can simply do the following to send to the server.

IntStringFloat packet = new IntStringFloat("Example");
packet.testInt = 10;
packet.testString = "Hello";
packet.testFloat = 1.5f;

client.SendPacketToServer(packet);

This can then be received on the serverside:

'''
Clone this wiki locally