views:

1325

answers:

2

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?

+1  A: 

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.

AlexDrenea
+2  A: 

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

blowdart
the article is very nice, but I found that it sends the data in serial to the connected clients , this means if a client closed the his application during sending the system will wait till timeout occur , this happens to me when I applied the same code, how can I solve this (make timeout very small?)
Ahmed Said
You can solve it by either, as you say, reducing the timeout for the backward call, or, more sensibly, putting the callbacks into background worker threads, so they run in parallel. It was only a demo :)
blowdart