.NET Remoting - Events, Events? Events!

Introduction

 
You have the server and several clients. You want the server to fire an event and all of the clients or only some specific must receive it. This article describes several approaches to the problem.
 
By events, I particular mean a process satisfying to the following statements:
  1. The caller sends the same message to several receivers.
  2. All calls are performed concurrently.
  3. The caller finally gets to know the receiver's replies.
I hope the first statement does not require any additional explanation.
 
All calls are performed concurrently. If connection to the specific client is slow (or is broken), sending to other clients will not be delayed until that specific client replies (or server recognizes clients unavailability via time-out).
 
The third statement stems from the real business needs. Usually a caller has to know whether recipients successfully receive the message. Also it would be good to gather recipients' replies also, when it is possible.
 
Using the code (the first solution) .NET Native Events
 
Let's study the first sample. Well-known layer contains delegate declaration and public available event.
  1. ///  
  2. /// Is called by the server when a message is sent.  
  3. ///  
  4. public delegate void MessageDeliveredEventHandler(string message);  
  5. ///  
  6. /// ChatRoom provides common methods for chatting.  
  7. ///  
  8. public interface IChatRoom {  
  9.   ///  
  10.   /// Sends the message to all clients.  
  11.   ///  
  12.   /// Message to send.  
  13.   void SendMessage(string message);  
  14.   ///  
  15.   /// Message delivered event.  
  16.   ///  
  17.   event MessageDeliveredEventHandler MessageDelivered;  

In my implementation the caller calls SendMessage method, which, in its turn, fires the event. This call can be made directly by a client though.
 
Clients create delegate instances pointed to MarshalByRefObject-derived class and add handlers to the event. The only issue here is that delegate should point to well-known class, so as a work-around I declared well-known class that just calls late-bound method (MessageReceiver class).
  1. IChatRoom iChatRoom = (IChatRoom) Activator.GetObject(typeof(IChatRoom), "gtcp://127.0.0.1:8737/ChatRoom.rem");  
  2. iChatRoom.MessageDelivered += new MessageDeliveredEventHandler(messageReceiver.MessageDelivered);  
  3. // ... ask user to enter the message  
  4. // and force the event  
  5. iChatRoom.SendMessage(str);  
  6. // Server provides an instance implementing IChatRoom interface.  
  7. ///  
  8. /// Sends the message to all clients.  
  9. ///  
  10. /// Message to send.  
  11. public void SendMessage(string message) {  
  12.   Console.WriteLine("\"{0}\" message will be sent to all clients.", message);  
  13.   if (this.MessageDelivered != null)  
  14.     this.MessageDelivered(message);  
  15. }  
  16. ///  
  17. /// Message delivered event.  
  18. ///  
  19. public event MessageDeliveredEventHandler MessageDelivered; 
What we've got finally with this approach?
 
The pros:
  • Very easy to implement if all business objects are located in well-known layer.
The cons:
  • Late-binding is required for business objects located in "unknown for clients" DLL.
  • Calls are made consecutively. The next client will be called only when the previous one returns a result.
  • If a client is unreachable or throws an exception, invoking is stopped and all remain clients will not receive the message.
  • You should manage sponsorship separately. 
You can mark MessageReceiver.MessageDelivered method with one-way attribute to solve the second problem. But you should understand that there is no way to get call results in this case. Disconnected clients will never get excluded from the events recipient list. It's like a memory leak.
  1. [OneWay]  
  2. public void MessageDelivered(string message)  
  3. {  
  4.   if (this.MessageDeliveredHandler != null)  
  5.     this.MessageDeliveredHandler(message);  

Summary

 
This scheme is completely unacceptable. It is slow, unreliable, and does not fit my conditions.
 
You can use this scheme for short-living affairs that do not have too many clients and each client should have a possibility to break an event process.
 
Using the code (the second solution). Interface-based approach

Let's study the second sample. Known layer contains event provider interface and client receiver interface:
  1. ///  
  2. /// Describes a callback called when a message is received.  
  3. ///  
  4. public interface IChatClient {  
  5.   ///  
  6.   /// Is called by the server when a message is accepted.  
  7.   ///  
  8.   /// A message.  
  9.   object ReceiveMessage(string message);  
  10. }  
  11. ///  
  12. /// ChatRoom provides common methods for chatting.  
  13. ///  
  14. public interface IChatRoom {  
  15.   ///  
  16.   /// Sends the message to all clients.  
  17.   ///  
  18.   /// Message to send.  
  19.   void SendMessage(string message);  
  20.   ///  
  21.   /// Attaches a client.  
  22.   ///  
  23.   /// Receiver that will receive chat messages.  
  24.   void AttachClient(IChatClient iChatClient);  
  25. }  
  26. IChatClient interface must be implemented by any object which wants to receive chat messages.Client class implements IChatClient interface.  
  27. namespace Client {  
  28.   class ChatClient: MarshalByRefObject, IChatClient {  
  29.     static void Main(string[] args) {  
  30.       // client attaches to the event  
  31.       IChatRoom iChatRoom = (IChatRoom) Activator.GetObject(typeof(IChatRoom), "gtcp://127.0.0.1:8737/ChatRoom.rem");  
  32.       iChatRoom.AttachClient(new ChatClient());  
  33.       //... and asks user to enter a message.  
  34.       // Then fires the event  
  35.       iChatRoom.SendMessage(str);  
  36.       //...  
  37.     }  
  38.   }  

Server implements IChatRoom interface and allows attaching the clients. I keep clients in the hash only because I want to remove failed receivers quickly.
 
I added additional comments to the snippet below.
  1. class ChatServer: MarshalByRefObject, IChatRoom {  
  2.   ///  
  3.   /// Contains entries of MBR uri => client MBR implementing IChatClient interface.  
  4.   ///  
  5.   static Hashtable _clients = new Hashtable();  
  6.   ///  
  7.   /// Attaches the client.  
  8.   ///  
  9.   /// Client to be attached.  
  10.   public void AttachClient(IChatClient iChatClient) {  
  11.     if (iChatClient == null)  
  12.       return;  
  13.     lock(_clients) {  
  14.       //****************  
  15.       // I just register this receiver under MBR uri. So I can find and perform an  
  16.       // operation or remove it quickly at any time I will need it.  
  17.       _clients[RemotingServices.GetObjectUri((MarshalByRefObject) iChatClient)] = iChatClient;  
  18.     }  
  19.   }  
  20.   ///  
  21.   /// To kick off the async call.  
  22.   ///  
  23.   public delegate object ReceiveMessageEventHandler(string message);  
  24.   ///  
  25.   /// Sends the message to all clients.  
  26.   ///  
  27.   /// Message to send.  
  28.   /// Number of clients having received this  
  29.   /// message.  
  30.   public void SendMessage(string message) {  
  31.     lock(_clients) {  
  32.       Console.WriteLine("\"{0}\" message will be sent to all clients.", message);  
  33.       AsyncCallback asyncCallback = new AsyncCallback(OurAsyncCallbackHandler);  
  34.       foreach(DictionaryEntry entry in _clients) {  
  35.         // get the next receiver  
  36.         IChatClient iChatClient = (IChatClient) entry.Value;  
  37.         ReceiveMessageEventHandler remoteAsyncDelegate = new ReceiveMessageEventHandler(iChatClient.ReceiveMessage);  
  38.         // make up the cookies for the async callback  
  39.         AsyncCallBackData asyncCallBackData = new AsyncCallBackData();  
  40.         asyncCallBackData.RemoteAsyncDelegate = remoteAsyncDelegate;  
  41.         asyncCallBackData.MbrBeingCalled = (MarshalByRefObject) iChatClient;  
  42.         // and initiate the call  
  43.         IAsyncResult RemAr = remoteAsyncDelegate.BeginInvoke(message, asyncCallback, asyncCallBackData);  
  44.       }  
  45.     }  
  46.   }  
  47.   // Called by .NET Remoting when an async call is finished.  
  48.   public static void OurAsyncCallbackHandler(IAsyncResult ar) {  
  49.     AsyncCallBackData asyncCallBackData = (AsyncCallBackData)  
  50.     ar.AsyncState;  
  51.     try {  
  52.       object result = asyncCallBackData.RemoteAsyncDelegate.EndInvoke(ar);  
  53.       // the call is successfully finished and  
  54.       // we have call results here  
  55.     } catch (Exception ex) {  
  56.       // The call has failed.  
  57.       // You can analyze an exception  
  58.       // to understand the reason.  
  59.       // I just exclude the failed receiver here.  
  60.       Console.WriteLine("Client call failed: {0}.", ex.Message);  
  61.       lock(_clients) {  
  62.         _clients.Remove(RemotingServices.GetObjectUri(asyncCallBackData.MbrBeingCalled));  
  63.       }  
  64.     }  
  65.   }  

The pros:
  • All calls are made concurrently.
  • Failed receivers do not affect other receivers.
  • You can conduct any policies about failed receivers.
  • You know results of the calls and you can gather ref and out parameters.
The cons:
  • Much more complicated than the first scenario. 

Summary

 
This is exactly a pattern you should use if you need to implement an event and you use native channels. I did not implement attaching and detaching sponsors here, but you should definitely consider it if your clients do not hold on receivers.
 
Using the code (the third solution). Broadcast Engine
 
Let's do the same with Genuine Channels now. This approach looks like the previous one. But it is easier on the server-side and has absolutely different internal implementation.
 
Both known layer and client have absolutely the same implementation. We will find the difference only at the server.
 
Server constructs a Dispatcher instance that will contain a list of recipients:
  1. private static Dispatcher _dispatcher = new Dispatcher(typeof(IChatClient));  
  2. private static IChatClient _caller; 
To perform absolutely async processing, server attaches a handler and switches on async mode.
  1. static void Main(string[] args) {  
  2.   //...  
  3.   _dispatcher.BroadcastCallFinishedHandler += newBroadcastCallFinishedHandler(ChatServer.BroadcastCallFinishedHandler);  
  4.   _dispatcher.CallIsAsync = true;  
  5.   _caller = (IChatClient) _dispatcher.TransparentProxy;  
  6.   //...  

Each time the client wants to receive messages, the server puts it into dispatcher instance:
  1. ///  
  2. /// Attaches the client.  
  3. ///  
  4. /// Client to attach.  
  5. public void AttachClient(IChatClient iChatClient) {  
  6.   if (iChatClient == null)  
  7.     return;  
  8.   _dispatcher.Add((MarshalByRefObject) iChatClient);  

When the server wants to fire an event, it just calls a method on the provided proxy. This call will be automatically sent to all registered receivers:
  1. ///  
  2. /// Sends a message to all clients.  
  3. ///  
  4. /// Message to send.  
  5. /// Number of clients having received this message.  
  6. public void SendMessage(string message) {  
  7.   Console.WriteLine("\"{0}\" message will be sent to all clients.", message);  
  8.   _caller.ReceiveMessage(message);  

In my sample, I ignore call results. Anyway, Dispatcher will automatically exclude failed receivers after the 4th failure by default. But if I would like to do it, I will write something like this:
  1. public void BroadcastCallFinishedHandler(Dispatcher dispatcher, IMessage message, ResultCollector resultCollector) {  
  2.   lock(resultCollector) {  
  3.     foreach(DictionaryEntry entry in resultCollector.Successful) {  
  4.       IMethodReturnMessage iMethodReturnMessage = (IMethodReturnMessage) entry.Value;  
  5.       // here you get client responses  
  6.       // including out and ref parameters  
  7.       Console.WriteLine("Returned object = {0}", iMethodReturnMessage.ReturnValue.ToString());  
  8.     }  
  9.     foreach(DictionaryEntry entry in resultCollector.Failed) {  
  10.       string mbrUri = (string) entry.Key;  
  11.       Exception ex = null;  
  12.       if (entry.Value is Exception)  
  13.         ex = (Exception) entry.Value;  
  14.       else  
  15.         ex = ((IMethodReturnMessage) entry.Value).Exception;  
  16.       MarshalByRefObject failedObject = dispatcher.FindObjectByUri(mbrUri);  
  17.       Console.WriteLine("Receiver {0} has failed. Error: {1}", mbrUri, ex.Message);  
  18.       // here you have failed MBR object (failedObject)  
  19.       // and Exception (ex)  
  20.     }  
  21.   }  

You have all results gathered in one place, so you can make any decisions here.
 
Broadcast Engine has an asynchronous mode. In this mode, all calls are made concurrently, but it waits while all clients reply or time out expires. Sometimes its very useful, but this mode consumes one thread until call will be finished. Take a look at the Programming Guide which contains more details.
 

Summary

 
The pros
  • Easier to use than the second approach.
  • All calls are made concurrently.
  • Failed receiver will not affect other receivers.
  • Broadcast Engine automatically recognizes situations when the receiver is able to receive messages via true broadcast channel. If receivers did not receive a message via the true broadcast channel, Broadcast Engine repeats the sending of the message via the usual channel. So you can utilize IP multicasting with minimum effort.
  • Broadcast Engine takes care of the sponsorship of attached MBR receivers.
The cons
 
You still have to declare a well-known interface in order to implement events.