WCF系列教程之WCF客户端调用服务
1、創(chuàng)建WCF客戶端應(yīng)用程序需要執(zhí)行下列步驟
(1)、獲取服務(wù)終結(jié)點的服務(wù)協(xié)定、綁定以及地址信息
(2)、使用該信息創(chuàng)建WCF客戶端
(3)、調(diào)用操作
(4)、關(guān)閉WCF客戶端對象
?
二、操作實例
?
1、WCF服務(wù)層搭建:新建契約層、服務(wù)層、和WCF宿主,添加必須的引用(這里不會的參考本人前面的隨筆),配置宿主,生成解決方案,打開Host.exe,開啟服務(wù)。具體的代碼如下:
ICalculate.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks;namespace IService {[ServiceContract]public interface ICalculate{[OperationContract]int Add(int a, int b);} }IUserInfo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Threading.Tasks;namespace IService {[ServiceContract]public interface IUserInfo{[OperationContract]User[] GetInfo(int? id);}[DataContract]public class User{[DataMember]public int ID { get; set; }[DataMember]public string Name { get; set; }[DataMember]public int Age { get; set; }[DataMember]public string Nationality { get; set; } } }注:必須引入System.Runtime.Serialization命名空間,應(yīng)為User類在被傳輸時必須是可序列化的,否則將無法傳輸
Calculate.cs
using IService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace Service {public class Calculate : ICalculate{public int Add(int a, int b){return a + b;}} }UserInfo.cs
using IService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace Service {public class UserInfo : IUserInfo{public User[] GetInfo(int? id){List<User> Users = new List<User>();Users.Add(new User { ID = 1, Name = "張三", Age = 11, Nationality = "China" });Users.Add(new User { ID = 2, Name = "李四", Age = 12, Nationality = "English" });Users.Add(new User { ID = 3, Name = "王五", Age = 13, Nationality = "American" });if (id != null){return Users.Where(x => x.ID == id).ToArray();}else{return Users.ToArray();}}} }Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Service; using System.ServiceModel;namespace Host {class Program{static void Main(string[] args){using (ServiceHost host = new ServiceHost(typeof(Calculate))){host.Opened += delegate { Console.WriteLine("服務(wù)已經(jīng)啟動,按任意鍵終止!"); };host.Open();Console.Read();}}} }App.Config
<?xml version="1.0"?> <configuration><system.serviceModel><services><service name="Service.Calculate" behaviorConfiguration="mexBehavior"><host><baseAddresses><add baseAddress="http://localhost:1234/Calculate/"/></baseAddresses></host><endpoint address="" binding="wsHttpBinding" contract="IService.ICalculate" /><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/></service></services><behaviors><serviceBehaviors><behavior name="mexBehavior"><serviceMetadata httpGetEnabled="true"/><serviceDebug includeExceptionDetailInFaults="true"/></behavior></serviceBehaviors></behaviors></system.serviceModel> </configuration>ok,打開Host.exe
服務(wù)開啟成功!
2、新建名為Client的客戶端控制臺程序,通過添加引用的方式生成WCF客戶端
確保Host.exe正常開啟的情況下,添加對服務(wù)終結(jié)點地址http://localhost:6666/UserInfo/的引用,,設(shè)置服務(wù)命名空間為UserInfoClientNS
點擊確定完成添加,生成客戶端代理類和配置文件代碼后,
開始Client客戶端控制臺程序?qū)CF服務(wù)的調(diào)用,Program.cs代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Client.UserInfoClientNS;namespace Client {class Program{static void Main(string[] args){UserInfoClient proxy =new UserInfoClient();User[] Users = proxy.GetInfo(null);Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}","ID","Name","Age","Nationality");for(int i=0;i<Users.Length;i++){Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}",Users[i].ID.ToString(),Users[i].Name.ToString(),Users[i].Age.ToString(),Users[i].Nationality.ToString());}Console.Read();}} }?
ok,第一種客戶端添加引用的方式測試成功
?
3、新建名為Client1的客戶端控制臺程序,通過svcutil.exe工具生成客戶端代理類的方式生成WCF客戶端,在VS2012 開發(fā)人員命令提示中輸入以下命令:
(1)、定位到當(dāng)前客戶端所在的盤符
(2)、定位當(dāng)前客戶端所在的路徑
?
(3)、svcutil?http://localhost:8000/OneWay/?wsdl?/o:OneWay.cs ? ? ?這里是OneWay,你本地是什么就是什么
(4)、生成客戶端代理類,生成成功之后,將文件添加到項目中
ok,生成成功!
(5)、將生成的文件包括到項目中,引入System.Runtime.Serialization命名空間和System.ServiceModel命名空間
(6)、確保服務(wù)開啟的情況下,開始調(diào)用,Program.cs代碼如下:
UserInfoClient proxy = new UserInfoClient();User[] Users = proxy.GetInfo(null);Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", "ID", "Name", "Age", "Nationality");for (int i = 0; i < Users.Length; i++){Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}",Users[i].ID.ToString(),Users[i].Name.ToString(),Users[i].Age.ToString(),Users[i].Nationality.ToString());}Console.Read();ok,服務(wù)調(diào)用成功,說明使用svcutil工具生成WCF客戶端的方式可行。
?
4、通過添加對Service程序集的引用,完成對WCF服務(wù)端的調(diào)用,新建一個Client2客戶端控制臺程序
先添加下面三個引用
using IService;
using System.ServiceModel;
using System.ServiceModel.Channels;
(1)、Program.cs代碼如下:
using System; using System.Collections.Generic; using System.Linq; using IService; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Threading.Tasks;namespace Client2 {class Program{static void Main(string[] args){EndpointAddress address = new EndpointAddress("http://localhost:6666/UserInfo/");WSHttpBinding binding = new WSHttpBinding();ChannelFactory<IUserInfo> factory = new ChannelFactory<IUserInfo>(binding, address);IUserInfo channel = factory.CreateChannel();User[] Users = channel.GetInfo(null);Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", "ID", "Name", "Age", "Nationality");for (int i = 0; i < Users.Length; i++){Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}",Users[i].ID.ToString(),Users[i].Name.ToString(),Users[i].Age.ToString(),Users[i].Nationality.ToString());}((IChannel)channel).Close();factory.Close();Console.Read();}} }ok,調(diào)用成功!
?
三、歸納總結(jié)
通過上面的代碼判斷WCF客戶端調(diào)用服務(wù)存在以下特點:
1、WCF服務(wù)端可客戶端通過使用托管屬性、接口、方法對協(xié)定進(jìn)行建模。若要連接到服務(wù)端的服務(wù),則需要獲取該服務(wù)協(xié)定的類型信息.獲取協(xié)定的類型信息有兩種方式:
(1)、通過Svcutil工具,在客戶端生成代理類的方式,來獲取服務(wù)端服務(wù)的服務(wù)協(xié)定的類型信息
(2)、通過給項目添加服務(wù)引用的方式
上面兩種方式都會從服務(wù)端的服務(wù)中下載元數(shù)據(jù),并使用當(dāng)前你使用的語言,將其轉(zhuǎn)換成托管源代碼文件中,同時還創(chuàng)建一個您可用于配置 WCF 客戶端對象的客戶端應(yīng)用程序配置文件.
2、WCF客戶端是表示某個WCF服務(wù)的本地對象,客戶端可以通過該本地對象與遠(yuǎn)程服務(wù)進(jìn)行通信。因此當(dāng)你在服務(wù)端創(chuàng)建了一個服務(wù)端協(xié)定,并對其進(jìn)行配置后,客戶端就可以通過生成代理類的方式(具體生成代理類的方式,上面已經(jīng)提了)和服務(wù)端的服務(wù)進(jìn)行通信,WCF 運行時將方法調(diào)用轉(zhuǎn)換為消息,然后將這些消息發(fā)送到服務(wù),偵聽回復(fù),并將這些值作為返回值或 out 參數(shù)(或 ref 參數(shù))返回到 WCF 客戶端對象中.(有待考證);
3、創(chuàng)建并配置了客戶端對象后,請創(chuàng)建一個 try/catch 塊,如果該對象是本地對象,則以相同的方式調(diào)用操作,然后關(guān)閉 WCF 客戶端對象。 當(dāng)客戶端應(yīng)用程序調(diào)用第一個操作時,WCF 將自動打開基礎(chǔ)通道,并在回收對象時關(guān)閉基礎(chǔ)通道。 (或者,還可以在調(diào)用其他操作之前或之后顯式打開和關(guān)閉該通道。)。不應(yīng)該使用 using 塊來調(diào)用WCF服務(wù)方法。因為C# 的“using”語句會導(dǎo)致調(diào)用 Dispose()。 它等效于 Close(),當(dāng)發(fā)生網(wǎng)絡(luò)錯誤時可能會引發(fā)異常。 由于對 Dispose() 的調(diào)用是在“using”塊的右大括號處隱式發(fā)生的,因此導(dǎo)致異常的根源往往會被編寫代碼和閱讀代碼的人所忽略。 這是應(yīng)用程序錯誤的潛在根源
?
轉(zhuǎn)載于:https://www.cnblogs.com/GreenLeaves/p/6859012.html
總結(jié)
以上是生活随笔為你收集整理的WCF系列教程之WCF客户端调用服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人口数量连续13年下滑:马斯克曾警告人口
- 下一篇: iOS 升级https的方案选择