Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send a notification message from server to all clients in WCF (broadcast you can say)?

I want to send notification message every second from net tcp WCF service to all clients, Broadcast you can say?

After the helpful answers

I wrote the following method that will send notifications (heartbeat) to all connected users

foreach (IHeartBeatCallback callback in subscribers)
{
  ThreadPool.QueueUserWorkItem(delegate(object state)
  {
    ICommunicationObject communicationCallback = (ICommunicationObject)callback;
    if (communicationCallback.State == CommunicationState.Opened)
    {
      try
      {
         callback.OnSendHeartBeat(_heartbeatInfo.message,    _heartbeatInfo.marketstart,_heartbeatInfo.marketend, _heartbeatInfo.isrunning,   DateTime.Now);
      }
      catch (CommunicationObjectAbortedException)
      {
        Logger.Log(LogType.Info, "BroadCast", "User aborted");
        communicationCallback.Abort();
      }
      catch (TimeoutException)
      {
       Logger.Log(LogType.Info, "BroadCast", "User timeout");
       communicationCallback.Abort();
      }
      catch (Exception ex)
      {
        Logger.Log(LogType.Error, "BroadCast", "Exception " + ex.Message + "\n" +  ex.StackTrace);
        communicationCallback.Abort();
      }

    }
    else
    {
      DeletionList.Add(callback);
    }
  }
  );
}

I am worried about calling the callback method as the client may close his application, but I handled it using the try catch, decrease the timeout, and send the broad cast in parallel, so is that sufficient?

like image 710
Ahmed Avatar asked Jun 17 '09 09:06

Ahmed


2 Answers

You'll need to setup a callback service; I wrote a simple beginners guide a while back

like image 157
blowdart Avatar answered Nov 10 '22 12:11

blowdart


In order to do that, you need to create and mantain a list of all connected clients (the general practice to fo this is creating LogIn and LogOut methods to create and manage a list of object representing your clients incuding their CallbackContext). Then, with a System.Time.Timers, you can loop through the connected client list and send the notification.

Tip. this method could also act as a Keep-Alive or Hear-Beat method (if this isn't it's purpose by design) by adding the possiblity to remove clients from your list if the service cannot send the callback to them.

like image 2
AlexDrenea Avatar answered Nov 10 '22 13:11

AlexDrenea