代码改变世界

创建简单的WCF服务

2010-09-03 19:29  coodoing  阅读(683)  评论(1编辑  收藏  举报

   1:基础知识介绍:

      和传统的分布式通信框架一样,WCF本质上提供一个跨进程、跨机器以致跨网络的服务调用。其中主要包括契约(Contract),绑定(Binding),地址(Address)。

     WCF的服务不能孤立地存在,需要寄宿于一个运行着的进程中,我们把承载WCF服务的进程称为宿主,为服务指定宿主的过程称为服务寄宿(Service Hosting)。在我们的计算服务应用中,采用了两种服务寄宿方式:通过自我寄宿(Self-Hosting)的方式创建一个控制台应用作为服务的宿主(寄宿进程为Hosting.exe);通过IIS寄宿方式将服务寄宿于IIS中(寄宿进程为IIS的工作进行W3wp.exe)。客户端通过另一个控制台应用模拟(进程为Client.exe)。下面主要是介绍自我寄宿方式创建服务宿主。

   2:创建标准的第一个WCF程序。

    首先创建一个空的解决方案:WCFCalculator

  

  右键点击解决方案选择Add->New Project并选择Console Application模板并选择名为项目名为Host(服务器端)

同理:右键点击解决方案选择Add->New Project并选择Console Application模板并选择名为项目名为Client(客户端)

右击项目Host,添加WCF Service,命名为Calculator

r

添加后,产生Calculator.cs,ICalculator.cs 以及app.config三个文件。

在ICalculator.cs中写服务契约:

namespace Host
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICalculator" in both code and config file together.
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double x, double y); //代表外部可以访问的服务
    }
}

然后Calculator.cs:

namespace Host
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Calculator" in both code and config file together.
    public class Calculator : ICalculator
    {
         public double Add(double x, double y)
        {
            return x + y;
        }
    }
}
在App.config中,将默认的baseAddress改成简短的baseAddress="http://localhost:8732/Calculator/"
然后通过自我寄宿的方式寄宿服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using System.ServiceModel;
using Host;
 
namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(Host.Calculator)))
            {
                host.Open();
                Console.ReadKey();
                host.Close();
            }
        }
    }
}

编译并生成Host.exe文件。这样服务已经成功寄宿在宿主端。
在WCFCalculator\Host\bin\Debug目录下启动Host.exe文件。【在添加service Refenrence过程中Host.EXE不能关闭】
在创建的Client项目中,右键点击Client项目并选择Add Service Reference...
在Address的TextBox里面输入服务器的地址http://localhost:8732/Calculator/,并点击Go,建立CalculatorWCF服务引用;

 这样,就可以在客户端进行WCF服务访问。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using Client.CalculatorWCF;
 
namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            CalculatorWCF.CalculatorClient client = new CalculatorClient();//创建客户端代理
            double result = client.Add(1.0,3.0);
            Console.WriteLine(result.ToString());
            Console.ReadKey(); 
        }  
)

这样客户端就可以访问服务器端的服务。运行结果:

参考文章:

http://www.cnblogs.com/ibillguo/archive/2008/04/14/1151872.html#1905158

http://www.cnblogs.com/artech/archive/2007/02/26/656901.html

 

 

  仅供同博友们分享所学点滴。附加上源代码:WCFCalculator.rar  Source