通过特定请求通过双重绑定向所有人发送消息?

时间:2011-10-09 20:46:26

标签: c# wcf

主要目标是让用户向主机发送消息。主持人会想两秒钟,然后用DUAL,会发回一条消息。这对我来说很好。

问题是,对于每个发送消息的用户,我都在订阅他。我想要完成的是,如果用户Console.Readline() == "b"(brodadcast)发送所有订阅者"Hello"

但订阅者列表服务Console.Readline() 位于主机

主持人:

static void Main(string[] args)
{
     ServiceHost duplex = new ServiceHost(typeof (ServiceClass));
     duplex.Open();
     Console.WriteLine("Press 'b' To Broadcast All subscibers : Hello");
     if (Console.ReadLine()=="b")
     {
         foreach (var registered in lstOfRegisteredUsers) //<== I cant access lstOfRegisteredUsers because its on the Service Class.
         {
              registered.SendBack("Hello");
         }
     }
     Console.WriteLine("Host is running, press <ENTER> to exit.");             
      Console.ReadLine();
}

服务:

public class ServiceClass : ISend
{
    public List<ISendBack> lstOfRegisteredUsers = new List<ISendBack>();

    public void Send(string data)
    {    
        ISendBack callback = OperationContext.Current.GetCallbackChannel<ISendBack>();
        lstOfRegisteredUsers.Add(callback); // <== here i'm adding subscribers for future broadcast " hello".
        Console.WriteLine("goind to process " + data);
        System.Threading.Thread.Sleep(2000);
        callback.SendBack("done " +data);
    }      
}

如何从主机发送给每个订阅者:“你好”?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么如果在托管您服务的控制台应用程序中收到按键输入,您希望向每个服务的回拨客户端广播一条消息吗?

要执行此操作,您需要能够从主机应用程序调用服务实例。

这可以通过在主机中创建服务类的实例来实现。然后,在创建ServiceHost时,将实例传递给ServiceHost构造函数。然后在你的服务中你有一个方法来进行实际的回调,你可以调用它。

例如:

// Create an instance of your service class
ServiceClass sc = new ServiceClass();

// Instantiate new ServiceHost and pass in the instance as a singleton
serviceHost = new ServiceHost(sc, "(Service uri here)");

// Call the method on the service (which then calls the clients)
sc.DoCallbacks();