Create a simple WCF Program (calculator) and a wcf program Calculator

Source: Internet
Author: User

Create a simple WCF Program (calculator) and a wcf program Calculator

In essence, WCF provides a cross-process, cross-machine, and cross-network service call. In this example, it mainly implements the calculator function. Most of the functions come from others' posts on the Internet, this is called standing on the shoulders of giants ~, However, in order to deepen your understanding of wcf, I decided to write a similar demo and display the problems encountered in the demo. I believe that for programmers who first know wcf, you may also encounter various problems. Now, proceed to the topic.

WCF is divided into four parts: 1. Contract 2. Service 3. WCF Host Program (console or IIS) 4. Client)

When writing wcf, I like to split the four parts into different class libraries for management.

1. Contract

The contract is an open Interface. The function name exposed to the client first creates a new wcf Service library named Interface ,:

Delete the default files (App. config, IService1.cs, Service1.cs) in the program and create ICalculator.

namespace Interface{    [ServiceContract(Name = "CalculatorService", Namespace = "http://www.artech.com/")]    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. Creating a service contract is actually a contract implementation class. Add "new project"-> WCF-> "WCF Service library" (for example, the same procedure is used to create a contract in the first step ), the class library name is Service,

After the creation is successful, delete the default file (App. config, IService1.cs, Service1.cs), add the reference "Interface" class library, create 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. Both the WCF contract and the service contract have been created. However, a program is required to carry these interfaces for external programs to call. Therefore, it is called a Host Program, the Host Program can be deployed on IIS or run on the console to facilitate debugging. The following describes how to use the console program as the host Program. Right-click the solution name and add "console program" named Hosting to add a reference to the Interface and Service.

There are two ways to enable the external function of wcf: one is the configuration file, which writes all the WCF information to the configuration file.

First, the relevant information of WCF 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" />        

 

 

The Main method code 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 has been started. Press any key to terminate the service! ") ;}; Host. Open (); Console. ReadLine ();}}}

Run the console program, as shown in:

Type 2: Write A WCFHelper class. When adding a help class, you must reference System. Runtime. Serialization and delete the application. config configuration for wcf. Otherwise, the error code is 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. I P, WCFHelper. port, "Calculator", "InspectService", WCFHelper. bindingProtocol. netTcp ). uri. absoluteUri); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior (); # if DEBUG behavior. httpGetEnabled = true; # else behavior. httpGetEnabled = false; # endif host. description. behaviors. add (behavior); host. opened + = delegate {Console. writeLine ("CalculaorService has been started. Press any key to terminate the service! ") ;}; Host. Open (); Console. ReadLine ();}}

 

 

4. After the Host Program is created, all the secrets of WCF can be accessed externally. 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 it, and open it as the administrator.

Next, right-click solution Name> Add Winform program to create WinForm program and add "service reference"

Add service reference (this reference method is "3. Add Host Program"-> "the second method of the WCF help class ")

Click "go to" to discover the WCF Service, as shown in:

 

Click "OK" to successfully reference the wcf. The following code starts to call the WCF program, for example, calling 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();

So far, the wcf program has completed running. Remember to run the Host Program and client program at the same time during debugging.

If you are not busy, vs can start multiple projects at the same time. You can also start the client and host at the same time.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.