WCF学习

2010-02-20  籽藤 

 ITSM项目中主要用到了Windows Service和WCF技术。尽管我不需要做技术实现,但还得抽空加强这方面的学习。

 首先说说为什么要用WCF。原因在于:WCF涵盖了之前微软推出的所有用于分布式开发的技术,如Remoting、Web Service、MSMQ等,并以一种统一的编程模式来实现。(如下表)

特性

Web Service

.NET Remoting

Enterprise Services

WSE

MSMQ

WCF

具有互操作性的Web服务

支持

 

 

 

 

支持

.NET到.NET的通信

 

支持

 

 

 

支持

分布式事务

 

 

支持

 

 

支持

支持WS标准

 

 

 

支持

 

支持

消息队列

 

 

 

 

支持

支持

 So,在.Net平台下开发面向服务的应用程序或分布式系统,WCF是最佳选择。

 ok,要说明WCF的通信过程还是得用程序说话。

(感谢这位仁兄的无私奉献:http://www.cnblogs.com/CharlesLiu/archive/2010/01/26/1655781.html

 在一个解决方案(WCF)下创建3个项目:Host(Console Application)、HelloworldService(Class Library)、Client(Console Application)。三个项目都需要添加System.ServiceModel引用。如下图:

 在HelloworldService项目中添加Service.cs。代码如下:

namespace HelloworldService
{
    [ServiceContract]
    public interface IService {

        [OperationContract]
        string HelloWorld(string message);
    }

    public class Service:IService
    {
        public string HelloWorld(string message) {
           
            return string.Format("At {0},I will say {1}", DateTime.Now, message);
        }
    }
}

 在Host项目中添加Host.cs。代码如下:

namespace HelloworldService
{
    public  class Host
    {
        static void Main(string[] args)
        {

            using (ServiceHost host = new ServiceHost(typeof(HelloworldService.Service)))
            {
                host.AddServiceEndpoint(typeof(HelloworldService.IService), new WSHttpBinding(), "http://localhost:9000/HelloWorld"); ;
                host.Open();
                Console.WriteLine("Host in started successful!");
                Console.Read();
            }

        }
    }
}

在Client项目中添加Client.cs。代码如下:

namespace HelloworldService
{
    [ServiceContract]
    public interface IService {

        [OperationContract]
        string HelloWorld(string message);
    }


    class Client
    {
        static void Main(string[] args)
        {
            IService proxy = ChannelFactory<IService>.CreateChannel(new WSHttpBinding(), new EndpointAddress("http://localhost:9000/HelloWorld"));
            string message = proxy.HelloWorld("Hello, World - Apple");
            Console.WriteLine(message);
            Console.ReadLine();

        }
    }
}

先运行Host,再运行Client。结果如下:



通过程序可以看出,WCF封装了消息的通信细节,引入Endpoint元素,集地址、绑定(即:通信方式)和契约(即:通信接口)三位为一体。之所以要用到System.ServiceModel,也是为了让程序可使用Contract属性标签,这正是客户端和服务端通信的契约。



========================

Wo,总算对WCF有点概念了。在程序运行的过程中,曾报错“HTTP 无法注册URL http://+:9000/HelloWorld/”。我的系统是Vista,这说明需要提升程序或Visual Studio.Net的权限。最简单的解决办法是:“以管理员身份运行”重新打开Visual Studio。



 

 

 

 

 

 

379°/3797 人阅读/0 条评论 发表评论

登录 后发表评论