WCF学习笔记(二):简单调用

一个通信会话过程有两个部分组成,客户端和服务端,他们要进行会话就必然有共同的语言约定,在WCF中这称为契约(contract),定义好通信的约定后,服务端需要确定服务的具体内容,即为配置、运行服务、开放终结点。客户端描述如何从 WCF 服务检索用于创建 WCF 客户端的元数据。

第一、建立契约 

代码
using  System;
using  System.ServiceModel;
 
namespace  Microsoft.ServiceModel.Samples
{
  ServiceContract(Namespace 
=  “http: // wengyuli”)] 
   public   interface  ICalculator
  {
     [OperationContract]
     
double  Add( double  n1,  double  n2);
   }
}

 

第二、实现契约

public   class  CalculatorService : ICalculator
{
    
public   double  Add( double  n1,  double  n2)
   {
      
double  result  =  n1  +  n2;
      
return  result;
    }
}

 

第三、发布服务 

代码
static   void  Main( string [] args)

        {

            Uri baseAddress 
=   new  Uri( " http://localhost:8000/wengyuli/Service " );

            ServiceHost serviceHost 
=   new  ServiceHost( typeof (CalculatorService), baseAddress);

            
try

            {

                serviceHost.AddServiceEndpoint(
typeof (ICalculator),  new  WSHttpBinding(),  " CalculatorService " );

                ServiceMetadataBehavior smb 
=   new  ServiceMetadataBehavior();

                smb.HttpGetEnabled 
=   true ;

                serviceHost.Description.Behaviors.Add(smb);

                serviceHost.Open();

                Console.WriteLine(
" The service is ready. " );

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

                Console.WriteLine();

                Console.ReadLine();

                serviceHost.Close();

            }

            
catch  (CommunicationException ce)

            {

                Console.WriteLine(
" An exception occured: {0} " , ce.Message);

                serviceHost.Abort();

            }

        }

 

第四、调用服务

代码
static   void  Main( string [] args)

        {

            
// Create an instance of the WCF Client.

            System.ServiceModel.EndpointAddress epAddress 
=   new  EndpointAddress( " http://localhost:8000/wengyuli/Service/CalculatorService " );

            CalculatorClient client 
=   new  CalculatorClient( new  WSHttpBinding(), epAddress);

            
int  value1  =   2 ;

            
int  value2  =   5 ;

            
int  result  =  client.Add(value1, value2);

            Console.WriteLine(
" Add({0},{1}) = {2} " , value1, value2, result);

            client.Close();

            Console.WriteLine();

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

            Console.ReadLine();

        }

 

你可能感兴趣的:(学习笔记)