您好,登錄后才能下訂單哦!
這篇文章主要介紹wcf如何實現計算器功能,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
WCF本質上提供一個跨進程、跨機器以致跨網絡的服務調用 ,本示例中 主要實現了計算器的功能,大部分的函數來源于網上別人的帖子,這叫站在巨人的肩膀上,O(∩_∩)O哈哈~,但是為了加深自己的對wcf的理解,因此決定自己在寫個類似的demo,把寫demo中遇到的問題展現出來,我相信對于初識wcf的程序員了來說,也會遇到各種問題。好了步入正題。
WCF 分為四個部分 1、契約(Interface)2、服務契約(Service)3、WCF 宿主程序(控制臺或者IIS) 4、客戶端(Client)
本人在寫wcf的時候喜歡將四個部分分別拆分成不同的類庫來管理。
1、契約
契約是對外開放的接口,暴露給客戶端的函數名稱首先,新建一個wcf服務庫,名稱為Interface,如圖所示:
刪掉程序中默認的文件(App.config,IService1.cs,Service1.cs),新建ICalculator
namespace Interface { [ServiceContract(Name = "CalculatorService", Namespace = "")]public interface ICalculator { [OperationContract]double Add(double x, double y); [OperationContract]double Subtract(double x, double y); [OperationContract]double Multiply(double x, double y); [OperationContract]double Divide(double x, double y); } }
2、新建服務契約,其實就是實現契約的類 ,添加"新建項目"->WCF->"WCF服務庫" (如 第一步新建契約是一樣的步驟),類庫的名稱為Service,
新建成功后,刪除默認文件(App.config,IService1.cs,Service1.cs),添加引用"Interface" 類庫,新建CalculatorService 并實現ICalculator
namespace Service { [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]public class CalculatorService : ICalculator {public double Add(double x, double y) {return x + y; }public double Subtract(double x, double y) {return x - y; }public double Multiply(double x, double y) {return x * y; }public double Divide(double x, double y) {return x / y; } }
3、新建WCF宿主程序,WCF的契約和服務契約都已經建完,但是還需要一個程序來承載這些接口供外部程序調用,因此稱之為宿主程序,宿主程序可以部署在IIS上,也可以用控制臺程序運行方便調試,下面我就介紹用控制臺程序作為宿主程序。在解決方案的名稱右鍵添加"控制臺程序" 名稱為Hosting ,添加對Interface和Service的引用
實現wcf對外開放有兩種方式,一種方式是配置文件,將所有的WCF信息都寫到配置文件中
第一種:WCF的相關信息寫到配置文件(App.config)中
<?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/> </startup> <system.serviceModel> <services> <service name="Service.CalculatorService" behaviorConfiguration="WCFService.WCFServiceBehavior"> <endpoint address="http://127.0.0.1:8888/CalculatorService" binding="wsHttpBinding" contract="Service.Interface.ICalculator"> </endpoint> <endpoint address="net.tcp://127.0.0.1:9999/CalculatorService" binding="netTcpBinding" contract="Service.Interface.ICalculator"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://127.0.0.1:8888/"/> <add baseAddress="net.tcp://127.0.0.1:9999/"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WCFService.WCFServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
Main方法的主要代碼如下,
public class Program {internal static ServiceHost host = null;static void Main(string[] args) {using (ServiceHost host = new ServiceHost(typeof(CalculatorService))) { host.Opened += delegate{ Console.WriteLine("CalculaorService已經啟動,按任意鍵終止服務!"); }; host.Open(); Console.ReadLine(); } } }
運行控制臺程序,如下圖所示:
第二種:寫一個WCFHelper類,添加幫助類的時候,一定引用System.Runtime.Serialization ,并且刪掉App.config 對wcf的配置,否則會報錯代碼如下:
public static class WCFHelper {public static string IP { get; set; }public static int Port { get; set; }static WCFHelper() {try{ IP = System.Environment.MachineName;// ConfigurationManager.AppSettings["ServiceIP"];// Port = int.Parse(ConfigurationManager.AppSettings["ServicePort"]); }catch{ } EndpointAddress.Add(BindingProtocol.Http, "http://{0}:{1}/{2}/{3}"); EndpointAddress.Add(BindingProtocol.NetTcp, "net.tcp://{0}:{1}/{2}/{3}");//EndpointAddress.Add(BindingProtocol.NetMsmq, "net.msmq://{0}:{1}/" + schema + "/{2}");//EndpointAddress.Add(BindingProtocol.NetPipe, "net.pipe://{0}:{1}/" + schema + "/{2}");try{ httpBinding = new BasicHttpBinding(); httpBinding.MaxBufferSize = 200065536; httpBinding.MaxReceivedMessageSize = 200065536; httpBinding.CloseTimeout = new TimeSpan(0, 10, 0); httpBinding.OpenTimeout = new TimeSpan(0, 10, 0); httpBinding.ReceiveTimeout = new TimeSpan(0, 10, 0); httpBinding.SendTimeout = new TimeSpan(0, 1, 0); httpBinding.Security.Mode = BasicHttpSecurityMode.None; httpBinding.ReaderQuotas.MaxDepth = 64; httpBinding.ReaderQuotas.MaxStringContentLength = 2147483647; httpBinding.ReaderQuotas.MaxArrayLength = 16384; httpBinding.ReaderQuotas.MaxBytesPerRead = 4096; httpBinding.ReaderQuotas.MaxNameTableCharCount = 16384; }catch{ httpBinding = new BasicHttpBinding(); }try{ tcpBinding = new NetTcpBinding(); tcpBinding.CloseTimeout = new TimeSpan(0, 1, 0); tcpBinding.OpenTimeout = new TimeSpan(0, 1, 0); tcpBinding.ReceiveTimeout = new TimeSpan(0, 10, 0); tcpBinding.SendTimeout = new TimeSpan(0, 1, 0); tcpBinding.TransactionFlow = false; tcpBinding.TransferMode = TransferMode.Buffered; tcpBinding.TransactionProtocol = TransactionProtocol.OleTransactions; tcpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; tcpBinding.ListenBacklog = 100000; tcpBinding.MaxBufferPoolSize = 524288; tcpBinding.MaxBufferSize = 200065536; tcpBinding.MaxConnections = 2000; tcpBinding.MaxReceivedMessageSize = 200065536; tcpBinding.PortSharingEnabled = true; tcpBinding.Security.Mode = SecurityMode.None; tcpBinding.ReaderQuotas.MaxDepth = 64; tcpBinding.ReaderQuotas.MaxStringContentLength = 2147483647; tcpBinding.ReaderQuotas.MaxArrayLength = 163840000; tcpBinding.ReaderQuotas.MaxBytesPerRead = 4096; tcpBinding.ReaderQuotas.MaxNameTableCharCount = 16384; tcpBinding.ReliableSession.Ordered = true; tcpBinding.ReliableSession.InactivityTimeout = new TimeSpan(0, 10, 0); tcpBinding.ReliableSession.Enabled = false; }catch{ tcpBinding = new NetTcpBinding(); } }private static BasicHttpBinding httpBinding;public static BasicHttpBinding HttpBinding {get{return httpBinding; } }private static NetTcpBinding tcpBinding;public static NetTcpBinding TcpBinding {get{return tcpBinding; } }public static EndpointAddress GetEndpointAddress(string ip, int port, string serviceSchema, string serviceName, BindingProtocol protocol) {string address = EndpointAddress[protocol]; address = string.Format(address, ip, port, serviceSchema, serviceName);return new EndpointAddress(address); }public static EndpointAddress GetEndpointAddress(string serviceSchema, string serviceName, BindingProtocol protocol) {string address = EndpointAddress[protocol]; address = string.Format(address, IP, Port, serviceSchema, serviceName);return new EndpointAddress(address); }public static Uri GetBaseAddress(string ip, int port, string serviceSchema, string serviceName, BindingProtocol protocol) {string address = EndpointAddress[protocol]; address = string.Format(address, ip, port + 1, serviceSchema, serviceName);return new Uri(address); }public static Uri GetBaseAddress(string serviceSchema, string serviceName, BindingProtocol protocol) {string address = EndpointAddress[protocol]; address = string.Format(address, IP, Port + 1, serviceSchema, serviceName);return new Uri(address); }private readonly static Dictionary<BindingProtocol, string> EndpointAddress = new Dictionary<BindingProtocol, string>();public enum BindingProtocol { Http = 1, NetTcp = 2,//NetPipe = 3,//NetMsmq = 4 } }
將 宿主程序中的main方法改成如下:
static void Main(string[] args) { WCFHelper.IP = "127.0.0.10"; WCFHelper.Port = 9999; Uri httpUri = WCFHelper.GetBaseAddress(WCFHelper.IP, WCFHelper.Port, "Calculator", "Inspect", WCFHelper.BindingProtocol.Http);using (ServiceHost host = new ServiceHost(typeof(CalculatorService), httpUri)) { host.AddServiceEndpoint(typeof(ICalculator), WCFHelper.TcpBinding, WCFHelper.GetEndpointAddress(WCFHelper.IP, WCFHelper.Port, "Calculator", "InspectService", WCFHelper.BindingProtocol.NetTcp).Uri.AbsoluteUri); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();#if DEBUGbehavior.HttpGetEnabled = true;#elsebehavior.HttpGetEnabled = false;#endifhost.Description.Behaviors.Add(behavior); host.Opened += delegate{ Console.WriteLine("CalculaorService已經啟動,按任意鍵終止服務!"); }; host.Open(); Console.ReadLine(); } }
4、宿主程序建完了,WCF的所有鍥約已經對外可以訪問了,那現在需要建立Client 去調用wcf程序了 ,
首先,編譯宿主程序Host,找到bin/debug/ Host.exe 右鍵管理員打開,如果如下圖證明服務已經于寧
其次,在解決方案名稱->右鍵添加Winform程序 新建WinForm 程序,添加"服務引用"
添加服務引用 (此引用方式,是以"3、添加宿主程序" ->"第二種 WCF幫助類的方式")
點擊“轉到” 系統發現WCF服務,如下圖所示:
點擊確定,就成功的將wcf的引用了,下面開始調用WCF的程序了,例如調用Add方法,代碼如下:
ServiceReference1.CalculatorServiceClient client = new ServiceReference1.CalculatorServiceClient(); textBox3.Text = client.Add(double.Parse(textBox1.Text), double.Parse(textBox2.Text)).ToString();
到此為止,wcf程序已經完成的跑通了,記得 調試的時候已經把宿主程序和client程序同時運行。
如果閑麻煩,vs 支持同時啟動多個項目,可以同時把client 和host同時啟動
以上是wcf如何實現計算器功能的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。