WCF essentially provides a cross-process, cross-machine and even cross-network service call. In this example, it mainly implements the function of the calculator. Most of the functions come from other people's posts on the Internet. This is called standing on the shoulders of giants. , O(∩_∩)O haha~, but in order to deepen my understanding of wcf, I decided to write a similar demo myself to show the problems encountered in writing the demo. I believe that for those who are new to wcf program As an employee, you will also encounter various problems. Okay, let’s get to the point.
WCF is divided into four parts 1. Contract (Interface) 2. Service Contract (Service) 3. WCF host program (console or IIS) 4. Client (Client)
Myself When writing wcf, I like to split the four parts into different class libraries for management.
1. Contract
The contract is an interface open to the outside world. The function name exposed to the client. First, create a new wcf service library named Interface, as shown in the figure:
Delete the default files in the program (App.config, IService1.cs, Service1.cs) and create a new 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. Create a new service The contract is actually the class that implements the contract. Add "New Project"->WCF->"WCF Service Library" (the first step is the same as creating a new contract). The name of the class library is Service,
After the creation is successful, delete the default files (App.config, IService1.cs, Service1.cs), add a reference to the "Interface" class library, create a new CalculatorService and implement 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. Create a new WCF host program. The WCF contract and service contract have been completed, but a program is still needed to host these interfaces for external program calls, so it is called a host program. The host program can Deployed on IIS, you can also use the console program to run for easy debugging. Below I will introduce using the console program as the host program. Right-click on the name of the solution and add "Console Program" with the name Hosting and add references to Interface and Service.
There are two ways to open WCF to the outside world. One way is to configure the file to add all WCF information. All are written to the configuration file
The first type: WCF related information is written to the configuration file (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>
The main code of the Main method is as follows,
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(); } } }
Run the console program, as shown below:
Second type: Write a WCFHelper class. When adding the helper class, be sure to reference System.Runtime.Serialization and delete the wcf configuration in App.config. Otherwise, the error code will be reported as follows:
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 } }
Change the main method in the host program to the following:
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. The host program is built, and all the steps of WCF It is now accessible to the outside world, so now you need to create a Client to call the wcf program.
First, compile the host program Host, find bin/debug/Host.exe, right-click the administrator to open it, if the following picture proves that the service has been Yu Ning
Secondly, add Winform program by right-clicking on the solution name -> New WinForm program, add "Service Reference"
Add service reference (this The reference method is "3. Add host program" ->"The second WCF help class method")
## Click "Go" and the system finds the WCF service, as shown in the figure below: Click OK to successfully reference the wcf, let's start Call the WCF program, for example, call the Add method. The code is as follows:ServiceReference1.CalculatorServiceClient client = new ServiceReference1.CalculatorServiceClient(); textBox3.Text = client.Add(double.Parse(textBox1.Text), double.Parse(textBox2.Text)).ToString();
The above is the detailed content of Understanding of wcf--implementing the calculator function. For more information, please follow other related articles on the PHP Chinese website!