2011-09-26 113 views
2

我一直在浏览互联网一段时间,但找不到符合我的具体问题的任何内容。如果有人能够简洁地解释这一点,我将不胜感激。WCF服务和Windows应用程序客户端的帮助

基本上我想从我的客户端(Windows应用程序)调用WCF Web服务,此服务将执行更新。不过,我希望服务能够以进度方式“回调”客户端,以便用户通过可视化进度条查看正在发生的事情。这可以做到吗?

我看过的具有回调在其中,并尝试写一些代码,但不具有最大的运气确实让这些回调火,我大致了解wsDualHttpBinding之间的磨难全双工WCF服务的概念和netTcpBinding,但不能真正得到任何工作。

目前我的测试运行在同一个盒子上,即Windows应用程序和WCF服务(运行关闭http://localhost:58781/)。我知道一旦这些转向生产环境,我可能会得到更多的问题,所以我现在想要考虑这些问题。

任何帮助,这将不胜感激。

+0

肯定看一看由GertArnold – EtherDragon

回答

2

这是具有自托管服务和客户端的准系统示例。

合同

[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(); 
     } 
    } 
} 

这使用一个双工信道OV er net.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 
+0

添加的链接这是伟大的,但你将如何使用这不典型的console.writeline?而是更新进度条? – Coesy

+1

那么在WinForms中,您可以简单地使用窗体实现IService1Callback并更新Progress(...)的实施进度条。 –

+0

您可能想要查看:http://www.dotnetdude.com/CategoryView,category,WCF.aspx –