帮助WCF服务和Windows应用程序客户端

本文关键字:应用程序 客户端 Windows WCF 服务 帮助 | 更新日期: 2023-09-27 18:09:58

我在互联网上找了一段时间,但找不到适合我确切问题的任何东西。如果有人能简明扼要地解释一下,我会很感激的。

基本上我想从我的客户端(Windows应用程序)调用WCF web服务,该服务将执行更新。然而,我希望服务"回调"到客户端与进度,这样用户可以看到什么是通过一个可视化的进度条。这能做到吗?

我看过全双工WCF服务的想法,其中有回调,并试图写一些代码,但没有最大的运气,实际上得到这些回调火,我大致知道关于wsDualHttpBinding和netttcpbinding之间的磨难,但不能真正得到工作。

目前我的测试是运行在同一个盒子,即windows应用程序和WCF服务(运行http://localhost:58781/)。我知道一旦这些转移到生产环境中,我可能会遇到更多的问题,所以我希望现在就把这些考虑进去。

帮助WCF服务和Windows应用程序客户端

这是一个带有自托管服务和客户端的裸机示例。

[ServiceContract(CallbackContract = typeof(IService1Callback), SessionMode=SessionMode.Required)]
public interface IService1
{
    [OperationContract]
    void Process(string what);
}
public interface IService1Callback
{
    [OperationContract]
    void Progress(string what, decimal percentDone);
}
服务器

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : IService1
{
    public void Process(string what)
    {
        Console.WriteLine("I'm processing {0}", what);
        for (int i = 0; i < 10; i++)
        {
            OperationContext.Current.GetCallbackChannel<IService1Callback>().Progress(what, (i+1)*0.1M);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        using (ServiceHost host = new ServiceHost( typeof(Service1), new Uri[] { new Uri("net.tcp://localhost:6789") }))
        {
            host.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(SecurityMode.None), "Service1");
            host.Open();
            Console.ReadLine();
            host.Close();
        }
    }
}

public class CallbackHandler : IService1Callback
{
    public void Progress(string what, decimal percentDone)
    {
        Console.WriteLine("Have done {0:0%} of {1}", percentDone, what);
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Setup the client
        var callbacks = new CallbackHandler();
        var endpoint = new EndpointAddress(new Uri("net.tcp://localhost:6789/Service1"));
        using (var factory = new DuplexChannelFactory<IService1>(callbacks, new NetTcpBinding(SecurityMode.None), endpoint))
        {
            var client = factory.CreateChannel();
            client.Process("JOB1");
            Console.ReadLine();
            factory.Close();
        }
    }
}

使用网络上的双工信道。TCP,由服务器触发通信,通知客户端进度更新。

客户端显示:

Have done 10% of JOB1
Have done 20% of JOB1
Have done 30% of JOB1
Have done 40% of JOB1
Have done 50% of JOB1
Have done 60% of JOB1
Have done 70% of JOB1
Have done 80% of JOB1
Have done 90% of JOB1
Have done 100% of JOB1