Skip to content

SerializedMessages

Thomas Schwotzer edited this page Aug 14, 2021 · 6 revisions

Messages are disseminated in your ASAP P2P system. The actual message structure is opaque to the system. Your message content is of type byte[]. It is your task to produce this byte array and to deserialize received messages. You can implement both methods as you please. Nevertheless, there are some experiences we have made after implementing several apps. We want to share this best practise.

Implement a message class

public class YourMessage {
    public static YourMessage produceYourMessage(/* your message parts */) { ... }
    public static YourMessage produceYourMessage(byte[] serializedMessage) { ... }
    public byte[] serialize() { ..}
}

This code sketches a message class. It provides two static factory methods: one produces a message object by your parameters. The other one produces a message object from its serialized format. The third – and only non static – method serializes this message.

Lets assume we implement a messenger. A message my contain a string (message content) and a timestamp. Their would be code somewhere in your application:

...
CharSequence message = ... // message e.g. from GUI
long timestamp = System.currentTimeMillis();
...

Your message object could look like this:

public class YourMessage {
    private CharSequence message;
    private long timestamp;

    public static YourMessage produceYourMessage(CharSequence message, long timestamp) { 
        this.message = message, this.timestamp = timestamp;
    }
    public static YourMessage produceYourMessage(byte[] serializedMessage) { ... }
    public byte[] serialize() { .. }
}

SharkMessage

Clone this wiki locally