0

我正在使用 WsDualHttpBinding 绑定来实现 WCF 异步服务以进行双工通信以获取数据库更改。

我已经实现了服务,但我不知道如何从客户端应用程序中调用它。

这是代码。

下面的代码是 WCF 服务

[ServiceContract()]
public interface ICustomerService
{
       [OperationContract(IsOneWay = true)]
        void GetAllCustomer();
}


public interface ICustomerServiceCallback
{
    [OperationContract(IsOneWay = true)]
    void Callback(Customer[] customers);
}


[ServiceContract(Name = "ICustomerService",
    CallbackContract = typeof(CustomerServiceLibrary.ICustomerServiceCallback),
    SessionMode = SessionMode.Required)]
public interface ICustomerServiceAsync
{
    [OperationContract(AsyncPattern = true)]
    IAsyncResult BeginGetAllCustomer(AsyncCallback callback, object asyncState);
    void EndGetAllCustomer(IAsyncResult result);
}

[DataContract]
public class Customer
{
    [DataMember]
    public string Name
    {
        get;
        set;
    }


}

}

public class CustomerService :ICustomerService,IDisposable
{

    List<Customer> Customers = null;
    ICustomerServiceCallback callback;
    Customer customer = null;

    string constr = "Data Source=.;Initial Catalog=WPFCache;Persist Security Info=True;User ID=sa;Password=Password$2";

    public CustomerService()
    {
        callback = OperationContext.Current.GetCallbackChannel<ICustomerServiceCallback>();
        SqlDependency.Start(constr);
    }


    public void GetAllCustomer()
    {

            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    con.Open();

                    cmd.Connection = con;
                    cmd.CommandText = "GetHero";
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Notification = null;

                    // Create the associated SqlDependency
                    SqlDependency dep = new SqlDependency(cmd);
                    dep.OnChange += new OnChangeEventHandler(dep_OnChange);

                    SqlDataReader dr = cmd.ExecuteReader();
                    Customers = new List<Customer>();
                    while (dr.Read())
                    {
                        customer = new Customer();
                        customer.Name = dr.GetString(0);

                        Customers.Add(customer);

                    }
                }

                callback.Callback(Customers.ToArray());


            }

    }

    void dep_OnChange(object sender, SqlNotificationEventArgs e)
    {
        try
        {

            if (e.Type == SqlNotificationType.Change)
            {
               GetAllCustomer();
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }


    public void Dispose()
    {
        SqlDependency.Stop(constr);
    }
}

我已将此 WCF 异步服务托管为控制台应用程序中的自托管。

这里是托管代码

类程序{

    static void Main(string[] args)
    {
        StartService();

    }

    internal static ServiceHost myServiceHost = null;

    internal static void StartService()
    {
        Uri httpbaseAddress = new Uri("http://localhost:8087/CustomerService/");

        Uri[] baseAdresses = { httpbaseAddress };

        myServiceHost = new ServiceHost(typeof(CustomerServiceLibrary.CustomerService));
        myServiceHost.AddServiceEndpoint(typeof(CustomerServiceLibrary.ICustomerService), new WSDualHttpBinding(), httpbaseAddress);

        ServiceDescription serviceDesciption = myServiceHost.Description;

        foreach (ServiceEndpoint endpoint in serviceDesciption.Endpoints)
        {

            Console.WriteLine("Endpoint - address:  {0}", endpoint.Address);
            Console.WriteLine("         - binding name:\t\t{0}", endpoint.Binding.Name);
            Console.WriteLine("         - contract name:\t\t{0}", endpoint.Contract.Name);
            Console.WriteLine();

        }

        myServiceHost.Open();
        Console.WriteLine("Press enter to stop.");
        Console.ReadKey();

        if (myServiceHost.State != CommunicationState.Closed)
            myServiceHost.Close();

    }

}

在客户端应用程序中创建了一个 DuplexChannel 工厂实例这是代码。

  private void Window_Loaded(object sender, RoutedEventArgs e)
    {
       EndpointAddress address = new EndpointAddress(new   Uri("http://localhost:8087/CustomerService"));
        WSDualHttpBinding wsDualBinding = new WSDualHttpBinding();
        DuplexChannelFactory<ICustomerServiceAsync> client = new    DuplexChannelFactory<ICustomerServiceAsync>(new InstanceContext(this), wsDualBinding, address);
        App.channel = client.CreateChannel();
    }

现在我的问题是如何调用

  • 开始获取所有客户
  • EndGetAllCustomer

我的服务方法。

帮助我.... 非常感谢提前...

4

1 回答 1

1

你需要:

  InstanceContext instanceContext = new InstanceContext(YOUR_OBJECT_IMPLMENTS_CALLBACK);

using (App.channel as IDisposable)
{
    App.channel.YOUR_METHOD_HERE();
} 

这个例子:

endPointAddr = "net.tcp://" + textBox2.Text + ":8000/FIXMarketDataHub";
                NetTcpBinding tcpBinding = new NetTcpBinding();
                tcpBinding.TransactionFlow = false;
                tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
                tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
                tcpBinding.Security.Mode = SecurityMode.None;

                EndpointAddress endpointAddress = new EndpointAddress(endPointAddr);

                Append("Attempt to connect to: " + endPointAddr);

                InstanceContext instanceContext = new InstanceContext(??);

                IMarketDataPub proxy = DuplexChannelFactory<IMarketDataPub>.CreateChannel(instanceContext,tcpBinding, endpointAddress);

                using (proxy as IDisposable)
                {
                    proxy.Subscribe();
                    Append("Subscribing to market data");                    
                }  

另请参阅微软示例

于 2013-03-28T21:33:16.017 回答