微软在VS2008中集成了WCF -- Windows Communication Foundation 一个全新的数据通讯方式
WCF中,我们可以看到Remoting,WebServices,Enterprise Services 的影子,它对服务的交互,类型转换,数据传送等等进行了大量的封装,支持各种协议,并且提供了许多模块,提高开发的效率。WCF是微软SOA策略的重要组成部分,可以将WCF看过一条线,用来创建各种服务。
      开始我们的HelloWorld: 
      创建三个项目: 1. name:HelloWCF   Type: WCF Service Library. 
                           2. name:Host          Type: Console Application.
                           3. name:  Client        Type: Console Application.

       HelloWCF项目,系统已经自动创建了名为:IService1的服务契约(ServiceContract),并且向外界暴露两个操作(OperationContract):GetData 和GetDataUsingDataContract, 并且定义了数据契约(DataContract):CompositeType.

Service1 实现了IService1接口在GetData操作:

 public string GetData(int value)
        
{
            
return string.Format("You entered: {0}", value);
        }

  
public CompositeType GetDataUsingDataContract(CompositeType composite)
        
{
            
if (composite.BoolValue)
            
{
                composite.StringValue 
+= "Suffix";
            }

            
return composite;
        }

对Host项目添加引用:System.ServiceModel 和 HelloWCF
加入代码:
static void Main(string[] args)
        
{
            
using (ServiceHost host = new ServiceHost(typeof(HelloWCF.Service1)))
            
{
                host.AddServiceEndpoint(
typeof(HelloWCF.IService1), new NetTcpBinding(), "net.tcp://localhost:1000/HelloWCF");
                host.Open();
                Console.Read();
            }

        }

对Client项目添加引用:System.ServiceModel 和 项目HelloWCF
加入代码:
 static void Main(string[] args)
        
{
            IService1 proxy 
= ChannelFactory<IService1>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:1000/HelloWCF"));
            String result 
= proxy.GetData(88);
            Console.WriteLine(result);
            Console.Read();
        }
设定Host为启动项目:
启动控制台,设定Client启动项目,运行,你可以看到显示:You entered: 88 调用服务器成功!
posted on 2008-05-30 20:50  Injun  阅读(2201)  评论(2)    收藏  举报