WCF:如何从wcf服务触发客户端的事件

时间:2012-10-30 19:04:53

标签: wcf

假设我有一个小的wcf服务,它有双工连接,我希望在我的客户端没有方法回调,而是应该触发一个事件。然后如何重构我的代码。我的代码如下。

服务器端

namespace CommonParts
{
[ServiceContract(Namespace = "rf.services", 
    CallbackContract = typeof(IDataOutputCallback), 
    SessionMode = SessionMode.Required)]
public interface IServerWithCallback
{
    [OperationContract(IsOneWay=true)]
    void StartDataOutput(string msg);
}


public interface IDataOutputCallback {
    [OperationContract(IsOneWay = true)]
    void SendDataPacket(string data);
}
}

namespace RF.WCF.Callback.Server
{
class ServerWCallbackImpl : IServerWithCallback
{
    #region IServerWithCallback Members

    public void StartDataOutput(string msg)
    {
        //OperationContext.Current.
        IDataOutputCallback callback = OperationContext.Current.GetCallbackChannel<IDataOutputCallback>();
        for (int i = 0; i < 10; i++)
        {
            Random r = new Random();
            int interval = r.Next(500,3000);
            System.Threading.Thread.Sleep(interval);
            //callback.SendDataPacket("Packet " + i.ToString());
            callback.SendDataPacket("Hello " + msg);
        }
        callback.SendDataPacket("Last packet is this one :)");
    }
    #endregion
}
}

class Program
{
    static void Main(string[] args)
    {
        var myBinding = new NetTcpBinding(SecurityMode.None);
        ServiceHost duplex = new ServiceHost(typeof(ServerWCallbackImpl));
        duplex.AddServiceEndpoint(typeof(IServerWithCallback),
            myBinding,
            "net.tcp://192.168.1.2:9080/DataService");
        duplex.Open();
        Console.WriteLine("Host is running, press <ENTER> to exit.");
        Console.ReadLine();
        duplex.Close();
    }
}

客户端

class CallbackImpl : IDataOutputCallback

{     #region IDataOutputCallback会员

public void SendDataPacket(string data)
{
  Console.WriteLine("Server sent: {0}", data);
}

#endregion

}

static void Main(string[] args)
{
    var myBinding = new NetTcpBinding(SecurityMode.None);
  DuplexChannelFactory<IServerWithCallback> cf =
          new DuplexChannelFactory<IServerWithCallback>(
              new CallbackImpl(),
              myBinding,
              new EndpointAddress("net.tcp://192.168.1.2:9080/DataService")); 
  IServerWithCallback srv = cf.CreateChannel();
  Console.Write("Enter Value... ");
  srv.StartDataOutput(Console.ReadLine());
  Console.WriteLine("Start");
  Console.ReadLine();
}

当以下行将从客户端执行时称为 srv.StartDataOutput(Console.ReadLine());

然后将调用StartDataOutput()函数,并从此函数调用一个名为 callback.SendDataPacket(“Hello”+ msg); 然后 SendDataPacket()将在客户端调用函数。

所以我的问题是如何在客户端触发事件而不是回调函数

1 个答案:

答案 0 :(得分:0)

事件驱动的WCF异步服务的一个很好的教程是here at Code Project. 它应该为您的工作提供良好的开端。此示例中的一个关键语句是该过程与进行回调调用没有太大区别。 :)