-
Notifications
You must be signed in to change notification settings - Fork 25
The Datapackage
A Datapackage is nothing but a serializable ArrayList containing Objects, whose first element is called ID.
Just create an object from the class Datapackage and give the constructor a String called 'ID' (so the Datapackage can be identified by the remote program later) and at least one and a maximum of many arbitrary objects as payload. For example:
Datapackage myDatapackage = new Datapackage("CHAT_MSG_IDENTIFIER", aUsername, aMessage, aPicture);
User the sendMessage methods provided by Client and Server classes. For example let the client send the above Datapackage to the server:
client.sendMessage(myDatapackage);
And that's all.
Datapackages that are not sent in response to a different packet, but initial from the server or client, are handled by registering handlers. This usually happens in the Server's preStart method or the Client's constructor. For example as a client let's handle Datapackages with an ID String that equals 'SOME_MESSAGE_IDENTIFICATION':
registerMethod("SOME_MESSAGE_IDENTIFICATION", new Executable() {
@Override
public void run(Datapackage msg, Socket socket) {
doSomethingWith(msg);
}
});
If a client sends a Datapackage to a server it always waits for the server to send a reply Datapackage. This package is returned by the sendMessage function. This Datapackage contains the default reply ID 'REPLY' on the first index, all other elements (index 1 to size()-1) are payload and can be processed. For example:
Datapackage replyFromServer = client.sendMessage(myDatapackage);
System.out.println(replyFromServer.id()); // REPLY
processSomePayload(replyFromServer.get(1));
processSomeRestOfThePayload(replyFromServer.get(2));
Be careful when implementing handler methods on you server: Always send a reply using sendReply(...). Otherwise the requesting client will never stop waiting for the answer package.