C # writing WCF Simple server and client

Source: Internet
Author: User
Tags hosting

Http://www.wxzzz.com/1860.html

Windows Communication Foundation (WCF) is a series of application frameworks developed by Microsoft that support data communication and can be translated into the Windows Communications development platform. integrates the mechanisms of. NET Remoting,webservice,socket of the original Windows communication and incorporates the relevant technologies of HTTP and FTP. is the best practical way to develop distributed applications on the Windows platform.

Today, take a step-by-step implementation of WCF server and client development and basic explanation.

I. Creating a WCF project in Visual Studio

First open visual Studio (I'm using VS2013 here), and then create an empty solution named Wcfdemo.

Then create the 4 items listed below and make a relationship reference.

    • Contracts: It is a class library project that defines a contract and adds an assembly to a reference to the project System.ServiceMode ;
    • Services: It is a class library project for implementing a contract, so it is necessary to reference our Contracts project;
    • Hosting: A console application that implements the start of a WCF service that requires both referencing our Contracts projects and Services projects and referencing System.ServiceMode assemblies;
    • Client: A console application that also requires referencing the System.ServiceMode assembly;

Once created,:

Second, create service contract

First we need to create a contract (i.e. interface) in the contracts Project interface , where my contract specifies that 2 functions need to be implemented, namely to GetServerTime get the server's current time and GetServerName get the server name.

When writing code, it is important to note that you need to add ServiceContract a tag attribute to interface (indicating that the interface or class defines a service contract in a WCF application), and that the method of each contract requires OperationContract a tag attribute (indicating that the method defines an action, This operation is part of the service contract in the WCF application. Finally, the following code shows:

[ServiceContract]publicinterfaceigetserverinfo{[operationcontract]  Stringgetservertime();  [operationcontract]stringgetservername();}        

Third, the realization of the service contract

We have just created a contract in the contracts project, and IGetServerInfo now we need to create an implementation in the Services project that GetServerInfoService类 inherits the IGetServerInfo implementation, and I've written the following code to demonstrate , respectively, to obtain the server's current time, get the name of the server (I am here to demonstrate the direct return "Server Name:wxzzz" string to the client).

Public Class Getserverinfoservice:Igetserverinfo{ Public string getservertime ()  { return  Datetime. Now. Tostring} public string getservername ()  {  return  "Server name:wxzzz"  }}       /span>                

Iv. Starting a WCF service

A WCF service can create its own program to listen to services, or it can host IIS services. Let's start with our own program for the WCF Service listener.

WCF is a message-based communication framework that employs an endpoint (Endpoint)-based communication approach. Endpoints consist of three elements: address, binding (BIND), and contract (contract).

    • address: Address determines the location of the service;
    • binding: Bindings implement all the details of communication, including network transmission, message encoding, and other appropriate processing of messages for the implementation of certain functions such as security, reliable transmission, transactions, and so on. WCF has a series of system-defined bindings, such as BasicHttpBinding, Wshttpbinding, nettcpbinding, and so on;
    • Contract (Contract): A contract is an abstraction of a service operation, as well as a definition of the message exchange pattern and the message structure.

Based on these technical basics, here is the WCF service code block I wrote in Project hosting.

 Static void Main(String[]Args) { Using (ServiceHostHost= New ServiceHost(typeof(Getserverinfoservice))) {Host.AddServiceEndpoint(typeof(Igetserverinfo), New Wshttpbinding(), "Http://127.0.0.1:9999/getserverinfoservice"); If (Host.Description.Behaviors.Find<ServiceMetadataBehavior> () == Null) { ServiceMetadataBehaviorBehavior= New ServiceMetadataBehavior();Behavior.Httpgetenabled = True;Behavior.Httpgeturl = New Uri("Http://127.0.0.1:9999/getserverinfoservice/metadata");Host.Description.Behaviors.Add(Behavior } Host. Opened += delegate Span class= "pun" >{ console. Writeline (" Getserverinfoservice has been started, press any key to terminate the service! " };  Host. Openconsole. Read} }          /span>                

In the service boarding code provided above, we added for the creation ServiceHost ServiceMetadataBehavior , and adopted the Http-get -based metadata acquisition method, the metadata of the publishing address through ServiceMetadataBehavior the httpgeturl specified. After the ServiceHost invoked Open method has successfully hosted the service, we can obtain the service-related metadata from that address. Type Http://127.0.0.1:9999/getserverinfoservice/metadataon the address bar of the browser, and you will get the service metadata in the form of WSDL, as shown in.

Permissions issues:

If you cannot start the WCF service and prompt for an error: additional information: HTTP could not register for URL http://+:9999/getserverinfoservice/. The process does not have access to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for more information).

When you encounter this problem, close Visual Studio and then start Visual Studio with an administrator to open the project.

V. Client invocation of WCF service

After the WCF service we have written runs successfully, we can use the client to access the service side ( provided that the server must be in the running state ). So how does the client invoke the WCF service that we write, which is actually very simple, we take one step at a step to operate.

1. In the client project, click the right mouse button and select Add Service reference:

Then pop up the interface, we fill in the Address bar http://127.0.0.1:9999/getserverinfoservice/metadata and then click the "Go" button to see our services:

Then click OK, at which point the service is already referenced successfully. At this point we need to write the client code run and try to get the results we expect, the console code in theclient project is as follows:

 Static void Main(String[]Args) { ServiceReference1.GetserverinfoclientClient= New ServiceReference1.Getserverinfoclient(); StringStime=Client.GetServerTime(); console. Writeline ( "server time:"  + Stime string SName = client< Span class= "pun". getservername (); console. Writeline ( "server name:"  + Sname console. Read               /span>                

Once written, run (the WCF server must be turned on) try it, and the effect is as follows:

Well, we've basically completed a simple example of WCF server and client.

There are actually very, very many features, extensions, details, and so on in WCF that will continue to be stated in a later article.

This article sample source code download: Wcfdemo

C # writing WCF Simple server and client

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.