标签:
本节的主要内容:1、通过代理类的方式调用服务操作。2、通过通道的方式调用服务操作。3、代码下载
一、通过代理类的方式调用服务操作(两种方式添加代理类)
1.手动编写代理类,如下:
客户端契约:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.ServiceModel; 7 namespace y.WcfFirst.Client.Proxys 8 { 9 [ServiceContract] 10 public interface IHello 11 { 12 [OperationContract] 13 string Say(string name); 14 } 15 }
客户端代理类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.ServiceModel; 7 using System.ServiceModel.Channels; 8 namespace y.WcfFirst.Client.Proxys 9 { 10 public class HelloProxy:ClientBase<IHello>,IHello 11 { 12 public HelloProxy() 13 : base() 14 { 15 } 16 17 public string Say(string name) 18 { 19 return base.Channel.Say(name); 20 } 21 } 22 }
客户端app.config文件:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <system.serviceModel> 4 <client> 5 <endpoint name="wcfFirst" 6 address="net.tcp://localhost:6666/hello" 7 binding="netTcpBinding" 8 contract="y.WcfFirst.Client.Proxys.IHello"></endpoint> 9 </client> 10 </system.serviceModel> 11 </configuration>
客户端的调用:
1 using (HelloProxy proxy = new HelloProxy()) 2 { 3 Console.WriteLine("Recevie from Server:{0}", proxy.Say(name)); 4 proxy.Close(); 5 }
2.通过Metadata方式产生代理类。
服务端需要对app.config进行配置如下:
客户端的操作步骤:先运行服务端(host)。
a.在客户端点击Add Service Reference按钮,添加Service引用。如下图:
b.输入Address地址:http://localhost:8888,点击"GO",获取服务操作。并且重命名Namespace,如下图:
c.客户端对代理类的调用。
1 using (HelloClient clientProxy = new HelloClient()) 2 { 3 Console.WriteLine("Recevie from Server:{0}", clientProxy.Say(name)); 4 clientProxy.Close(); 5 }
二、通过通道方式调用服务操作
1.客户端契约,如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.ServiceModel; 7 namespace y.WcfFirst.ClientChannel.Proxy 8 { 9 [ServiceContract] 10 public interface IHello 11 { 12 [OperationContract] 13 string Say(string name); 14 } 15 }
2.客户端配置文件的设置:如下:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <system.serviceModel> 4 <client> 5 <endpoint name="wcfFirst" 6 address="net.tcp://localhost:6666/hello" 7 binding="netTcpBinding" 8 contract="y.WcfFirst.ClientChannel.Proxy.IHello"></endpoint> 9 </client> 10 </system.serviceModel> 11 </configuration>
3.客户端调用服务操作:如下:
1 ChannelFactory<IHello> factory = new ChannelFactory<IHello>("wcfFirst"); 2 IHello channelProxy = factory.CreateChannel(); 3 using(channelProxy as IDisposable) 4 { 5 Console.WriteLine("Recevie from Server:{0}", channelProxy.Say(name)); 6 }
标签:
原文地址:http://www.cnblogs.com/liuxiaoji/p/4538584.html