|
The .NET (C#) client and server can be compiled from within the Visual Studio IDE by opening the Calculator.sln
solution file.
The server program expects one parameter, which describes its intended listener address. The client part expects three parameters - the server's address and two integer values.
The client program is entirely implemented in the Client\Client.cs
file, which is dissected in detail below.
First the relevant import statements:
using System; using System.Threading; using Inspirel.YAMI;
The Inspirel.YAMI
namespace defines several important classes. The Agent
class is needed so that the client program can create its own agent that will manage the communication. The OutgoingMessage
class encapsulates the functionality of the outgoing message and the ability to track its progress. The Parameters
class allows to build a proper message content, where the string value will be placed.
The whole client program is implemented within the main function of the Client
class.
Initial actions in this procedure check whether there are three required arguments describing server destination address and two integer values:
namespace Calculator { class Client { static void Main(string[] args) { if(args.Length != 3) { Console.WriteLine( "expecting three parameters: " + "server destination and two integers"); return; } String serverAddress = args[0]; int a; int b; try { a = int.Parse(args[1]); b = int.Parse(args[2]); } catch(Exception) { Console.WriteLine("cannot parse the parameters"); return; }
After the program arguments are processed, client can create its own YAMI agent.
try { Agent clientAgent = new Agent();
Then the parameters object is prepared that will be used as a payload of the outgoing message - here it contains the two integer values that were read from the command-line with names ``a'' and ``b''. These names are recognized by the server.
Parameters param = new Parameters(); param.SetInteger("a", a); param.SetInteger("b", b);
When the parameters object is filled with data, the actual outgoing message is created:
OutgoingMessage message = clientAgent.Send(serverAddress, "calculator", "calculate", param);
Above, the Send()
function is invoked with the following parameters:
serverAddress
- The server target, as it was resolved on the server side when the server's listener was created; this is the string that was printed by the server just after starting and passed to the client program as its first argument."calculator"
- The logical destination object name; this name has to be known by the server agent, which is true if the message handler was registered there with this name. This name can be interpreted as the object name within the namespace of the server's agent."calculate"
- The message name, which is simply the name of the requested operation that the server should perform. In this particular example there is only one type of message that is sent from client to server, but in bigger systems this name will be certainly used by the server to figure out what to do. For example, the calculator system might be restructured to allow separate message for each basic operation (``add'', ``subtract'', ``multiply'' and ``divide'') - then, the message name would be a very natural mean for expressing the request.param
- The payload to be sent, which here contains two integer numbers from the command-line.The outgoing message object is created as a result of this operation.
It is important to note that the actual message is transmitted to the server in background and there is no provision for it to be already transmitted when the Send()
function returns. In fact, the user thread might continue its work while the message is being processed by the background I/O thread.
In this particular example, the client program does not have anything to do except waiting for the response:
message.WaitForCompletion();
Depending on the message state, client either processes the result or prints appropriate report on the console.
In the most expected case the completion of the message is a result of receiving appropriate reply from the server - this can be checked with the REPLIED
message state:
OutgoingMessage.MessageState state = message.State; if(state == OutgoingMessage.MessageState.REPLIED) { Parameters reply = message.Reply; int sum = reply.GetInteger("sum"); int difference = reply.GetInteger("difference"); int product = reply.GetInteger("product"); int ratio = 0; Parameters.Entry ratioEntry = reply.Find("ratio"); bool ratioDefined = ratioEntry != null; if(ratioDefined) { ratio = ratioEntry.GetInteger(); }
Above, the ratioDefined
variable is true
when the reply content has the entry for the result of division (and then the ratio
variable will get that value), and false
otherwise. This reflects the ``protocol'' of interaction between client and server that allows the server to send back the ratio only when it can be computed.
The code then prints all received values on the console:
Console.WriteLine("sum = {0}", sum); Console.WriteLine("difference = {0}", difference); Console.WriteLine("product = {0}", product); Console.Write("ratio = "); if(ratioDefined) { Console.WriteLine(ratio); } else { Console.WriteLine("<undefined>"); }
Alternatively, the message might be completed due to rejection or being abandoned - these cases are reported as well:
} else if(state == OutgoingMessage.MessageState.REJECTED) { Console.WriteLine( "The message has been rejected: {0}", message.ExceptionMsg); } else { Console.WriteLine( "The message has been abandoned."); }
The outgoing message manages some internal resources that need to be properly cleaned up. In this example, the whole program sends only one message, so both the agent and the message need to be cleaned up after they are no longer needed. In more complex systems a single agent will be used for processing many messages, so the clean-up pattern will be different as well.
message.Close(); clientAgent.Close();
The client program finishes with simple exception handling.
} catch(Exception ex) { Console.WriteLine("error: {0}" + ex.Message); } } } }
The server program is entirely implemented in the Server\Server.cs
file, which begins with a typical set of imports:
using System; using System.Threading; using Inspirel.YAMI;
One of the most important server-side entities is a message handler, which here is implemented in terms of a delegate. The protocol of this delegate is defined by Agent.IncomingMessageHandler
.
namespace Calculator { class Server { private static void calculator( object sender, IncomingMessageArgs args) {
The handler has to extract the content of the message, which is a regular parameters object that is available as a property of the args
argument. In the calculator system the content is supposed to have two integer entries named ``a'' and ``b'':
// extract the parameters for calculations Parameters param = args.Message.Parameters; int a = param.GetInteger("a"); int b = param.GetInteger("b");
The server computes the results of four basic calculations on these two numbers, with the possible omission of the ratio, which might be impossible to compute if the divisor is zero. In this case the ratio entry is simply not included in the resulting parameters object - note that the possibility of missing entry in the message response is properly handled by the client and this is part of the calculator ``protocol''.
// prepare the answer // with results of four calculations Parameters replyParams = new Parameters(); replyParams.SetInteger("sum", a + b); replyParams.SetInteger("difference", a - b); replyParams.SetInteger("product", a * b); // if the ratio cannot be computed, // it is not included in the response // the client will interpret that fact properly if(b != 0) { replyParams.SetInteger("ratio", a / b); }
Once the parameters object for the reply is prepared, the incoming message can be replied to:
args.Message.Reply(replyParams);
The handler finishes with a report on the console.
Console.WriteLine( "got message with parameters {0} and {1}" + ", response has been sent back", a, b); }
The Main()
function of the server program deals with command-line arguments, where the server target is expected.
static void Main(string[] args) { if(args.Length != 1) { System.Console.WriteLine( "expecting one parameter: server destination"); return; } string serverAddress = args[0];
Once the server target is known, it is passed to the freshly constructed agent in order to add a new listener. The resolved target that results from this operation is printed on the console.
try { Agent serverAgent = new Agent(); String resolvedAddress = serverAgent.AddListener(serverAddress); System.Console.WriteLine( "The server is listening on {0}", resolvedAddress);
The previously defined message handler is instantiated and registered as an implementation of the logical object named ``calculator''. This object name has to be known by clients so that they can properly send their messages.
serverAgent.RegisterObject("calculator", calculator);
The server's main thread effectively stops in the infinite loop. In this state the whole activity of the server program is driven by incoming messages that are received in background.
It should be noted that the background threads created by the agent are of the ``daemon'' type, which means that they alone are not able to keep the process alive. If the main thread was allowed to quit at this point, the whole server program would finish immediately without giving the clients any chance for interaction.
// block while(true) { Thread.Sleep(10000); }
The server code finishes with simple exception handling:
} catch(Exception ex) { Console.WriteLine("error: {0}", ex.Message); } } } }