WCF学习之旅(一)---Hello World.

本文通过一个简单的HelloWorld实例介绍了Windows Communication Foundation (WCF)的基本使用流程,包括定义服务契约、实现服务、配置宿主和服务客户端等关键步骤。

 

WCF学习之旅(一)---Hello World.

看了一些关于WCF的资料,从实例入手。记录自己学习WCF的过程。

从最简单的Hello World入门。

下图是我的solution及项目。

                                       

项目名称

功能

WCF.Client.Consoles

WCF客户端程序

WCF.Contracts

契约。接口程序

DataContract,ServiceContract,MessageContract

WCF.Host.Consoles

宿主程序

WCF.Proxys

客户端调用的代理类用SvcUtil.exe工具生成

WCF.Service.Web

发布service的站点。

WCF.ServiceLib

实现Contract的Library

 

Contract

IHello.cs

ContractedBlock.gif ExpandedBlockStart.gif Code
    [ServiceContract]
    
public interface IHello
    {
        [OperationContract]
        
void SayHello(string name);
    }

实现类

Hello.cs

ContractedBlock.gif ExpandedBlockStart.gif Code
    public class Hello:IHello
    {
        
#region IHello Members

        
public void SayHello(string name)
        {
            Console.WriteLine(
string.Format("Hello {0}", name));
        }

        
#endregion
    }

Service

Hello.svc

<%@ ServiceHost Language="C#" Debug="true" Service="Fastyou.WCF.ServiceLib.Hello" %>

Web.config

ContractedBlock.gif ExpandedBlockStart.gif Code
<system.serviceModel>
    
<services>
      
<service behaviorConfiguration="Fastyou.WCF.ServiceLib.HelloBehavior"
        name
="Fastyou.WCF.ServiceLib.Hello">
        
<endpoint address="" binding="basicHttpBinding" contract="Fastyou.WCF.Contracts.IHello">
          
<identity>
            
<dns value="localhost" />
          
</identity>
        
</endpoint>
        
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      
</service>
    
</services>
    
<behaviors>
      
<serviceBehaviors>
        
<behavior name="Fastyou.WCF.ServiceLib.HelloBehavior">
          
<serviceMetadata httpGetEnabled="true" />
          
<serviceDebug includeExceptionDetailInFaults="false" />
        
</behavior>
      
</serviceBehaviors>
    
</behaviors>
  
</system.serviceModel>

Host程序

ContractedBlock.gif ExpandedBlockStart.gif Code
        static void Main(string[] args)
        {
            
try
            {
                ServiceHost helloHost 
= new ServiceHost(typeof(Hello));
                helloHost.Opened 
+= delegate
                {
                    Console.WriteLine(
"服务已经启动!");
                    
                };
                helloHost.Open();
            }
            
catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
 

App.config

ContractedBlock.gif ExpandedBlockStart.gif Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    
<system.serviceModel>
        
<services>
            
<service name="Fastyou.WCF.ServiceLib.Hello" behaviorConfiguration="helloBehavior">
        
<host>
          
<baseAddresses>
            
<add baseAddress="http://localhost:8089/Hello"/>
          
</baseAddresses>
        
</host>
        
<endpoint address="Hello" binding="basicHttpBinding" contract="Fastyou.WCF.Contracts.IHello">
                    
<identity>
                        
<dns value="localhost"/>
                    
</identity>
                
</endpoint>
        
<endpoint binding="mexHttpBinding" contract="IMetadataExchange" address="mex" />
            
</service>
        
</services>
    
<behaviors>
      
<serviceBehaviors>
        
<behavior name="helloBehavior">
          
<serviceMetadata httpGetEnabled="true"/>
        
</behavior>
      
</serviceBehaviors>
    
</behaviors>
  
</system.serviceModel>
</configuration>

由于我的hello.svc是放在hello文件夹。所以这里的address 会有一个hello. baseAddress已经有一个Hello.

HelloProxys.cs

ContractedBlock.gif ExpandedBlockStart.gif Code

    [System.CodeDom.Compiler.GeneratedCodeAttribute(
"System.ServiceModel""3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName 
= "IHello")]
    
public interface IHello
    {

        [System.ServiceModel.OperationContractAttribute(Action 
= "http://tempuri.org/IHello/SayHello", ReplyAction = "http://tempuri.org/IHello/SayHelloResponse")]
        
void SayHello(string name);
    }

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

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute(
"System.ServiceModel""3.0.0.0")]
    
public partial class HelloClient : System.ServiceModel.ClientBase<IHello>, IHello
    {

        
public HelloClient()
        {
        }

        
public HelloClient(string endpointConfigurationName) :
            
base(endpointConfigurationName)
        {
        }

        
public HelloClient(string endpointConfigurationName, string remoteAddress) :
            
base(endpointConfigurationName, remoteAddress)
        {
        }

        
public HelloClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
            
base(endpointConfigurationName, remoteAddress)
        {
        }

        
public HelloClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
            
base(binding, remoteAddress)
        {
        }

        
public void SayHello(string name)
        {
            
base.Channel.SayHello(name);
        }
    }

Client的program.cs

ContractedBlock.gif ExpandedBlockStart.gif Code
static void Main(string[] args)
        {
            HelloWorld();
        }
        
static void HelloWorld()
        {
            
try
            {
                Console.WriteLine(
"-----------------------request begin-----------------------");
                
#region code for client;
                
//BasicHttpBinding bind = new BasicHttpBinding();
                
//EndpointAddress address = new EndpointAddress("http://localhost:8089/hello/hello");

                
//HelloClient ws = new HelloClient(bind, address);
                
//ws.SayHello("I'm fastyou. \r\n");
                
//ws.Close();
                #endregion

                
#region configuration for client

                HelloClient hc 
= new HelloClient("BasicHttpBinding_IHello");
                hc.SayHello(
"I'm fastyou. \r\n");
                hc.Close();

                
#endregion

                Console.WriteLine(
"-------------------------request end------------------------------------");
                Console.WriteLine(
"\r\n\r\n\r\n");
            }
            
catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.Read();
        }

App.config

ContractedBlock.gif ExpandedBlockStart.gif Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<system.serviceModel>
    
<bindings>
      
<basicHttpBinding>
        
<binding name="BasicHttpBinding_IHello" closeTimeout="00:01:00"
            openTimeout
="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
            allowCookies
="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
            maxBufferSize
="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
            messageEncoding
="Text" textEncoding="utf-8" transferMode="Buffered"
            useDefaultWebProxy
="true">
          
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
              maxBytesPerRead
="4096" maxNameTableCharCount="16384" />
          
<security mode="None">
            
<transport clientCredentialType="None" proxyCredentialType="None"
                realm
="" />
            
<message clientCredentialType="UserName" algorithmSuite="Default" />
          
</security>
        
</binding>
      
</basicHttpBinding>
    
</bindings>
    
<client>
      
<endpoint address="http://localhost:8089/Hello/Hello"
          binding
="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IHello"
          contract
="IHello" name="BasicHttpBinding_IHello" />
    
</client>
  
</system.serviceModel>
</configuration>

编译通过及配置好IIS后先运行host再运行Client.这时可以看到host程序中会出现hello,I’m XXX.

 

 代码下载

转载于:https://www.cnblogs.com/laihua/archive/2008/11/21/1338729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值