Skip to content

Packets

gcflames5 edited this page Aug 25, 2014 · 15 revisions

ServerInterconnect supports 2 types of Packets, a default Packet and a JsonPacket. These 2 packets are identical except in the way that they are serialized. A Packet requires the implementing class to specify read and write methods that read/write all relevant information to and from a data stream. A JsonPacket uses the GSON Library to serialize all the fields contained in the packet class into JSON.


Important! All packets must be registered when the application starts!

To register a packet:

PacketRegistry.registerPacket(MyPacket.class);

Creating a regular packet:

Packet Requirements:

  • A default constructor that is public and takes no args
  • A readPacketContent(DataInputStream input) method that populates instance variables from a DataInputStream
  • A writePacketContent(DataOutputStream output) method that writes instance variables to a DataOutputStream
public class NewPacket extends Packet{
    private String testString;

    public NewPacket(){} //MUST be present

    public NewPacket(String testString){
        this.testString = testString;
    }

    @Override
    public void readPacketContent(DataInputStream input) throws IOException {
        testString = PacketUtils.readString(input);
    }

    @Override
    public void writePacketContent(DataOutputStream output) throws IOException {
        PacketUtils.writeString(testString, output);     
    }
}

Remember to read and write in the same order!

Creating a JSON packet:

JSON Packet Requirements:

  • A default constructor that is public and takes no args
public class JsonMessagePacket extends JsonPacket {

    private String message;

    public JsonMessagePacket() {} //MUST be present

    public JsonMessagePacket(String message) {
        this.message = message;
    }

    public String getMessage() {
        return this.message;
    }
}

The JSON packet handles all the serialization for you so you don't have to worry about it!

Clone this wiki locally