Inspirel banner

Programming Distributed Systems with YAMI4

6.3.4 .NET

The following example is an extract from the calculator server that accepts the message from the client and computes the sum and difference of two numbers provided in the message payload. The message handler needs to be registered in the server-side agent so that incoming messages can be properly routed to it.

class Server
{
    private static void calculator(
        object sender, IncomingMessageArgs args)
    {
        Parameters param = args.Message.Parameters;

        int a = param.GetInteger("a");
        int b = param.GetInteger("b");

        Parameters replyParams = new Parameters();

        replyParams.SetInteger("sum", a + b);
        replyParams.SetInteger("difference", a - b);
 
        args.Message.Reply(replyParams);
    }
}

In the above example the calculator() function will be registered as a delegate and invoked by the agent whenever there is an incoming message addressed to the logical object for which the handler was registered.

The args parameter of the calculator() function has the Message property that refers to internal agent's structures and allows to initiate further communication that is needed to send the reply or rejection to the originating client program. Several operations can be executed on this message object and in this example the parameters object that was received as part of this message's payload is inspected with the Parameters property. Later, the reply is prepared based on the incoming parameters - in this example the server reads two values and computes their sum and difference and inserts both result values into a single parameters object that becomes the reply payload. After the Reply function is called on the incoming message object, the processing is completed and the agent can proceed with transmission of the reply to the client.

The above pattern is the most fundamental idiom for server-side processing of incoming messages and can be characterized by the fact that the complete message processing is contained in the scope of the callback invocation.

It is also possible to move the state of incoming message outside of the callback by simply copying the incoming message reference to another variable. This allows the server to process the incoming message asynchronously and outside of the handler callback.