现在的位置: 首页 > 综合 > 正文

WCF简单实例

2017年11月01日 ⁄ 综合 ⁄ 共 10509字 ⁄ 字号 评论关闭

 

一 简单示例结构

 [此实例纯手动实现,更简单地可以使用WCF的工程向导来创建wcf service,WCF Service也可以使用config文件,可以使用project的add referece来自动生成proxy和config]

 

二 WCFServer

1) wcfserver.cs文件如下:(需要引用system.servicemodel assembly)

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    
public interface ICalculator
    {
        
[OperationContract]
        
double Add(double n1, double n2);
        
[OperationContract]
        
double Subtract(double n1, double n2);
        
[OperationContract]
        
double Multiply(double n1, double n2);
        
[OperationContract]
        
double Divide(double n1, double n2);
    }

    // Service class that implements the service contract.
    
// Added code to write output to the console window.
    
public class CalculatorService : ICalculator
    {
        
public double Add(double n1, double n2)
        {
            
double result = n1 + n2;
            Console.WriteLine("Received 
Add({0},{1})", n1, n2);
            Console.WriteLine("
Return: {0}", result);
            
return result;
        }
        
public double Subtract(double n1, double n2)
        {
            
double result = n1 - n2;
            Console.WriteLine("Received Subtract({
0},{1})", n1, n2);
            Console.WriteLine("
Return: {0}", result);
            
return result;
        }
        
public double Multiply(double n1, double n2)
        {
            
double result = n1 * n2;
            Console.WriteLine("Received Multiply({
0},{1})", n1, n2);
            Console.WriteLine("
Return: {0}", result);
            
return result;
        }
        
public double Divide(double n1, double n2)
        {
            
double result = n1 / n2;
            Console.WriteLine("Received Divide({
0},{1})", n1, n2);
            Console.WriteLine("
Return: {0}", result);
            
return result;
        }
    }

    class WCFServer
    {
        static void Main(string[] args)
        {
            
// Step 1 of the address configuration procedure

            // Create a URI to serve as the base address.
            Uri baseAddress 
= new Uri("http://localhost:8000/ServiceModelSamples/Service");

            // Step 2 of the hosting procedureCreate ServiceHost
            ServiceHost selfHost 
= new ServiceHost(typeof(CalculatorService), baseAddress);

            try
            {
                // Step 3 of the hosting procedureAdd a service endpoint.
                selfHost.AddServiceEndpoint(
                    typeof(ICalculator),
                    new WSHttpBinding(),
                    "CalculatorService");

                // Step 4 of the hosting procedure: Enable metadata exchange.
                ServiceMetadataBehavior smb 
= new ServiceMetadataBehavior();
                smb.HttpGetEnabled 
= true;
                selfHost.Description.Behaviors.
Add(smb);

                // Step 5 of the hosting procedure: Start (and then stop) the service.
                selfHost.
Open();
                Console.WriteLine("The service 
is ready.");
                Console.WriteLine("Press 
<ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

                // Close the ServiceHostBase to shutdown the service.
                selfHost.
Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occurred: {
0}", ce.Message);
                selfHost.Abort();
            }
        }
    }
}

2) 运行wcfserver后,在浏览器中查看wcfserver提供的wcf service如下:(此时scfserver必须处于运行状态)

 

三 WCFClient (控制台程序)

1) 使用svcutil.exe生成wcfserver提供的wcf service的代理和wcfclient需要的config文件,如下:(此时scfserver必须处于运行状态)

"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\svcutil.exe" /language:cs /out:WCFClient\generatedProxy.cs /config:WCFClient\app.config http://localhost:8000/ServiceModelSamples/service

2)将生成的generatedproxy.cs和app.config加入wcfclient工程中,

generatedproxy.cs如下: 

代码

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.3615
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel""3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace
="http://Microsoft.ServiceModel.Samples", ConfigurationName="ICalculator")]
public interface ICalculator
{
    
    [System.ServiceModel.OperationContractAttribute(Action
="http://Microsoft.ServiceModel.Samples/ICalculator/Add", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse")]
    
double Add(double n1, double n2);
    
    [System.ServiceModel.OperationContractAttribute(Action
="http://Microsoft.ServiceModel.Samples/ICalculator/Subtract", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResponse")]
    
double Subtract(double n1, double n2);
    
    [System.ServiceModel.OperationContractAttribute(Action
="http://Microsoft.ServiceModel.Samples/ICalculator/Multiply", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResponse")]
    
double Multiply(double n1, double n2);
    
    [System.ServiceModel.OperationContractAttribute(Action
="http://Microsoft.ServiceModel.Samples/ICalculator/Divide", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideResponse")]
    
double Divide(double n1, double n2);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel""3.0.0.0")]
public interface ICalculatorChannel : ICalculator, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel""3.0.0.0")]
public partial class CalculatorClient : System.ServiceModel.ClientBase<ICalculator>, ICalculator
{
    
    
public CalculatorClient()
    {
    }
    
    
public CalculatorClient(string endpointConfigurationName) : 
            
base(endpointConfigurationName)
    {
    }
    
    
public CalculatorClient(string endpointConfigurationName, string remoteAddress) : 
            
base(endpointConfigurationName, remoteAddress)
    {
    }
    
    
public CalculatorClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            
base(endpointConfigurationName, remoteAddress)
    {
    }
    
    
public CalculatorClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            
base(binding, remoteAddress)
    {
    }
    
    
public double Add(double n1, double n2)
    {
        
return base.Channel.Add(n1, n2);
    }
    
    
public double Subtract(double n1, double n2)
    {
        
return base.Channel.Subtract(n1, n2);
    }
    
    
public double Multiply(double n1, double n2)
    {
        
return base.Channel.Multiply(n1, n2);
    }
    
    
public double Divide(double n1, double n2)
    {
        
return base.Channel.Divide(n1, n2);
    }
}

app.config如下: 

代码

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    
<system.serviceModel>
        
<bindings>
            
<wsHttpBinding>
                
<binding name="WSHttpBinding_ICalculator" closeTimeout="00:01:00"
                    openTimeout
="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal
="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize
="524288" maxReceivedMessageSize="65536"
                    messageEncoding
="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies
="false">
                    
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead
="4096" maxNameTableCharCount="16384" />
                    
<reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled
="false" />
                    
<security mode="Message">
                        
<transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm
="" />
                        
<message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite
="Default" establishSecurityContext="true" />
                    
</security>
                
</binding>
            
</wsHttpBinding>
        
</bindings>
        
<client>
            
<endpoint address="http://localhost:8000/ServiceModelSamples/Service/CalculatorService"
                binding
="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator"
                contract
="ICalculator" name="WSHttpBinding_ICalculator">
                
<identity>
                    
<userPrincipalName value="itech@example.com/>
                
</identity>
            
</endpoint>
        
</client>
    
</system.serviceModel>
</configuration>

3)wcfclient.cs文件如下: 

using System;
using System.ServiceModel;

namespace Microsoft.ServiceModel.Samples
{

    class WCFClient
    {
        
static void Main()
        {
            
//Step 1: Create an endpoint address and an instance of the WCF Client.
            CalculatorClient client = new CalculatorClient();

            // Step 2: Call the service operations.
            
// Call the Add service operation.
            double value1 = 100.00D;
            
double value2 = 15.99D;
            
double result = client.Add(value1, value2);
            Console.WriteLine(
"Add({0},{1}) = {2}", value1, value2, result);

            // Call the Subtract service operation.
            value1 = 145.00D;
            value2 
= 76.54D;
            result 
= client.Subtract(value1, value2);
            Console.WriteLine(
"Subtract({0},{1}) = {2}", value1, value2, result);

            // Call the Multiply service operation.
            value1 = 9.00D;
            value2 
= 81.25D;
            result 
= client.Multiply(value1, value2);
            Console.WriteLine(
"Multiply({0},{1}) = {2}", value1, value2, result);

            // Call the Divide service operation.
            value1 = 22.00D;
            value2 
= 7.00D;
            result 
= client.Divide(value1, value2);
            Console.WriteLine(
"Divide({0},{1}) = {2}", value1, value2, result);

            //Step 3: Closing the client gracefully closes the connection and cleans up resources.
            client.Close();

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();

        }
    }
}

 

4)运行wcfserver后如下:

 

四 其他

 

完!

【上篇】
【下篇】

抱歉!评论已关闭.