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

泄露秘密 提交于 2019-12-05 01:31:04

问题


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:


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




回答2:


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.



来源:https://stackoverflow.com/questions/1006058/how-can-i-send-a-notification-message-from-server-to-all-clients-in-wcf-broadca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!