Understanding WCF-Implementing the Calculator function

Source: Internet
Author: User
WCF essentially provides a cross-process, cross-machine, cross-network service invocation, this example mainly implements the function of the calculator, most of the functions are from the online people's posts, which is called standing on the shoulders of Giants, O (∩_∩) o haha ~, but in order to deepen their understanding of WCF, So decided to write a similar demo, to write a demo of the problems encountered in the show, I believe that the first knowledge of the WCF programmer, will also encounter various problems. Okay, step into the chase.

WCF is divided into four parts 1, Contracts (Interface) 2, service Contracts (services) 3, WCF host programs (console or IIS) 4, clients (client)

I like to write WCF when the four parts are divided into different class libraries to manage.

1. Contract

The contract is an open interface, exposing the function name to the client first, create a new WCF service library with the name interface:

Delete the default file (App.config,iservice1.cs,service1.cs) in the program 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, the new service contract, is actually the implementation of the contract class, add "New project"->wcf-> "WCF Service Library" (such as the first step to create a new contract is the same step), the name of the class library is service,

After the new success, delete the default file (App.config,iservice1.cs,service1.cs), add a reference to the "Interface" class library, create a new calculatorservice, and implement the 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, the new WCF host program, WCF's contract and service contract have been completed, but also need a program to host these interfaces for external program calls, so called host program, the host program can be deployed on IIS, can also be run with the console program for easy debugging, Here I will introduce the console program as the host program. In the name of the solution, right-click Add a "console program" named hosting, adding a reference to interface and service

There are two ways to make WCF open to the outside, one way is to configure the file to write all of the WCF information to the configuration file

First: Information about 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" cont ract= "Service.Interface.ICalculator" > </endpoint> <endpoint address= "Mex" binding= "Mexhttpbindin G "contract=" IMetadataExchange "/> <endpoint address=" Mex "binding=" mextcpbinding "contract=" IMetadataExchang            E "/> 

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 has started, press any key to terminate the service! ");                };                Host. Open ();                Console.ReadLine ();}}}    

Run the console program as shown in:

The second type: Write a Wcfhelper class, add Help class, you must refer to System.Runtime.Serialization, and delete the configuration of App. Config to 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["Se Rviceip "];//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 httpBi            nding;            }}private static nettcpbinding tcpbinding;public static nettcpbinding tcpbinding {Get{return tcpbinding; }}public static EndpointAddress getendpointaddress (string ip, int port, string serviceschema, String ser            Vicename, 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 addre            SS = 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> ();p ublic enum Bindingprotocol {Http = 1, nettcp = 2,//netpipe = 3,//NETMSMQ = 4 }    }

The

Changes 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 has started, press any key to terminate the service!                ");                }; Host.                Open ();            Console.ReadLine (); }}

4, the host program is finished, all WCF wedge has been externally accessible, it is now necessary to establish a client to invoke the WCF program,

First, compile the host program host and locate the Bin/debug/host.exe right-click Administrator to open if the service has because as proof

Next, in the solution name, right-click Add WinForm Program, new WinForm program, add "service Reference"

Add a service reference (this is referred to as "3, add host program," "The second type of WCF helper class")

Click on the "Go" system to discover the WCF service as shown in:

Click OK to successfully refer to the WCF, the following is the beginning of calling the WCF program, such as 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 run through, remember that the host program and the client program are running at the same time when debugging.

If you are busy, VS supports launching multiple projects at the same time, you can start both client and host simultaneously

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.