[WCF]利用net.tcp傳輸協定來建置WCF Service

 http://www.dotblogs.com.tw/puma/archive/2009/06/21/wcf-net-tcp-channelfactory-clientbase.aspx

最近很少在寫文章,也佷少在討論區解問題(因為工作很忙),所以沒什麼東西可以寫

這幾天無聊去看看WCF的東西,介紹給大家如何利用net.tcp傳輸協定來建置WCF Service


啓動WCF服務的方式有下列幾種方式:

1.利用Console或WinFrom方式
2.利用Windows Service方式
3.利用Web Server IIS方式


WCF支援的傳輸協定有下列幾種方式:

1.HTTP
2.net.tcp
3.net.pipe
4.net.msmq


存取WCF服務的Client端也可利用下列幾種方式:

1.WinForm or Console
2.ASP.NET or ASP.NET AJAX
3.WPF or Silverlight
...很多

首先準備下列專案:

WcfBase是給ConsoleHostWinFormClient共用的
ConsoleHostServer
WinFormClientClient

Server端啓動服務利用ServiceHost
Client端呼叫服務利用ClientBaseChannelFactory

此範例主要是利用Console來啓動WCF Service,利用WinForm來呼叫WCF Service

WcfBase(IHello.cs,Hello.cs)

IHello.cs

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05using System.ServiceModel;
06//加入System.ServiceModel參考
07  
08namespace WcfBase
09{
10    [ServiceContract]
11    publicinterface IHello
12    {
13        [OperationContract]
14        stringHelloWorld();
15    }
16}

Hello.cs

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05  
06namespace WcfBase
07{
08    publicclass Hello : IHello
09    {
10        publicstring HelloWorld()
11        {
12            return"HelloWorld";
13        }
14    }
15}

ConsoleHost(Program.cs,App.config)

Program.cs

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05using System.ServiceModel;
06//加入System.ServiceModel與WcfBase參考
07  
08namespace ConsoleHost
09{
10    classProgram
11    {
12        staticvoid Main(string[] args)
13        {
14            //WCF Console Host
15  
16            //此種方式需App.Config
17            ServiceHost host =new ServiceHost(typeof(WcfBase.Hello));
18            host.Open();
19            Console.WriteLine("WCF Service Start...");
20            Console.WriteLine("Press Enter to Stop WCF Service...");
21            Console.ReadLine();
22            host.Close();
23  
24            //此種方式不需App.Config
25            //ServiceHost host = new ServiceHost(typeof(WcfBase.Hello), new Uri("net.tcp://localhost:9000/"));
26            //host.AddServiceEndpoint(typeof(WcfBase.IHello), new NetTcpBinding(), "HelloService");
27            //host.Open();
28            //Console.WriteLine("WCF Service Start...");
29            //Console.WriteLine("Press Enter to Stop WCF Service...");
30            //Console.ReadLine();
31            //host.Close();
32        }
33    }
34}

App.config

01<?xmlversion="1.0"encoding="utf-8"?>
02<configuration>
03  <system.serviceModel>
04    <services>
05      <servicename="WcfBase.Hello">
06        <endpointaddress="HelloService"binding="netTcpBinding"contract="WcfBase.IHello"/>
07        <host>
08          <baseAddresses>
09            <addbaseAddress="net.tcp://localhost:9000/"/>
10          </baseAddresses>
11        </host>
12      </service>
13    </services>
14  </system.serviceModel>
15</configuration>

WinFormClient(FrmClient.cs,HelloClient.cs,App.config)

FrmClient.cs

01using System;
02using System.Collections.Generic;
03using System.ComponentModel;
04using System.Data;
05using System.Drawing;
06using System.Linq;
07using System.Text;
08using System.Windows.Forms;
09using System.ServiceModel;
10//加入System.ServiceModel與WcfBase參考
11  
12namespace WinFormClient
13{
14    publicpartial classFrmClient : Form
15    {
16        publicFrmClient()
17        {
18            InitializeComponent();
19        }
20  
21        privatevoid btnClientBase_Click(objectsender, EventArgs e)
22        {
23            //此種方式需App.Config
24            using(HelloClient client = newHelloClient())
25            {
26                client.Open();
27                MessageBox.Show(client.HelloWorld());
28            }
29  
30            //此種方式不需App.Config
31            //using (HelloClient client = new HelloClient( new NetTcpBinding(),new EndpointAddress("net.tcp://localhost:9000/HelloService")))
32            //{
33            //    client.Open();
34            //    MessageBox.Show(client.HelloWorld());
35            //}
36        }
37  
38        privatevoid btnChannelFactory_Click(objectsender, EventArgs e)
39        {
40            //此種方式需App.Config
41            using(ChannelFactory<WcfBase.IHello> channel = newChannelFactory<WcfBase.IHello>("Hello"))//指定ConfigName
42            {
43                WcfBase.IHello client = channel.CreateChannel();//CreateChannel後就會Open Channel
44                MessageBox.Show(client.HelloWorld());
45            }
46  
47            //此種方式不需App.Config
48            //using (ChannelFactory<WcfBase.IHello> channel = new ChannelFactory<WcfBase.IHello>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/HelloService")))
49            //{
50            //    WcfBase.IHello client = channel.CreateChannel();//CreateChannel後就會Open Channel
51            //    MessageBox.Show(client.HelloWorld());
52            //}
53        }
54    }
55}

HelloClient.cs

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05  
06namespace WinFormClient
07{
08    /// <summary>
09    /// 利用此類別來呼叫WCF Service,
10    /// </summary>
11    publicclass HelloClient : System.ServiceModel.ClientBase<WcfBase.IHello>, WcfBase.IHello
12    {
13        //沒有傳入任何Binding與EndpointAddress,會找App.Config的設定
14        publicHelloClient()
15        {
16  
17        }
18  
19        //依使用者定義的Binding與EndpointAddress,來設定
20        publicHelloClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)
21            :base(binding, remoteAddress)
22        {
23  
24        }
25  
26        publicstring HelloWorld()
27        {
28            returnbase.Channel.HelloWorld();
29        }
30    }
31}

App.config

1<?xmlversion="1.0"encoding="utf-8"?>
2<configuration>
3  <system.serviceModel>
4    <client>
5      <endpointname="Hello"address="net.tcp://localhost:9000/HelloService"binding="netTcpBinding"contract="WcfBase.IHello">
6      </endpoint>
7    </client>
8  </system.serviceModel>
9</configuration>


設定Config可以利用SvcConfigEditor.exe工具

參考網址:
http://msdn.microsoft.com/zh-tw/library/bb332338.aspx
http://www.devx.com/codemag/Article/33655/1763/page/1
http://www.codeproject.com/KB/WCF/WCFMultipleHosting.aspx
http://msdn.microsoft.com/zh-tw/library/ms732015.aspx

 

====

http://s.yanghao.org/program/viewdetail.php?i=51624

不费话了,小弟先行谢过,WCF的客户端中的核心类“CPCalculatorHello.cs”代码:

//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1433
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
问题一:这里的注释的意思是,代码是有工具生成的,神马意思?这种代码可以使用工具生成?


[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="CalculatorHello")]
问题二:这两句神马意思?有有神马作用?

public interface CalculatorHello
{
   
  [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/CalculatorHello/Add", ReplyAction="http://tempuri.org/CalculatorHello/AddResponse")]

问题三:这里的又是神马意思?有神吗作用?

  double Add(double n1, double n2);
   
  [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/CalculatorHello/HelloWorld", ReplyAction="http://tempuri.org/CalculatorHello/HelloWorldResponse")]
  void HelloWorld(string name);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface CalculatorHelloChannel : CalculatorHello, System.ServiceModel.IClientChannel
{
问题四:MSDN的解释为“定义出站请求的行为和客户端应用程序使用的请求/答复通道。”,这里应该是建立通道的方法的实现的接口了?

能不能扩展说下通道是怎样建立的,满足下小弟的求知欲。。。

}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class CalculatorHelloClient : System.ServiceModel.ClientBase<CalculatorHello>, CalculatorHello
{
问题五:System.ServiceModel.ClientBase<CalculatorHello>是什么?有神吗作用?

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

问题六:这个方法是干嘛使得?“base”MSDN上没找着啊???有神吗作用???

  {
  }
   
  public CalculatorHelloClient(string endpointConfigurationName, string remoteAddress) : 
  base(endpointConfigurationName, remoteAddress)
  {
  }
   
  public CalculatorHelloClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
  base(endpointConfigurationName, remoteAddress)
  {
  }
   
  public CalculatorHelloClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
  base(binding, remoteAddress)
  {
  }
   
  public double Add(double n1, double n2)
  {
  return base.Channel.Add(n1, n2);
这里就是调用服务器端的方法喽。。。

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

问题七:这些“【】”里的都是些神马东西,如果把它们去了,对程序的运行影响大吗???

 

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

http://baike.baidu.com/view/1140438.htm

概述  Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应用程序开发接口 可以翻译为Windows通讯接口,它是.NET框架的一部分,由 .NET Framework 3.0 开始引入,与 Windows Presentation Foundation及 Windows Workflow Foundation并行为新一代 Windows 操作系统以及 WinFX 的三个重大应用程序开发类库。在 .NET Framework 2.0 以及前版本中,微软发展了 Web Service (SOAP with HTTP communication),.NET Remoting (TCP/HTTP/Pipeline communication) 以及基础的 Winsock 等通信支持,由于各个通信方法的设计方法不同,而且彼此之间也有相互的重叠性(例如 .NET Remoting 可以开发 SOAP, HTTP 通信),对于开发人员来说,不同的选择会有不同的程序设计模型,而且必须要重新学习,让开发人员在使用中有许多不便。同时,面向服务架构(Service-Oriented Architecture) 也开始盛行于软件工业中,因此微软重新查看了这些通信方法,并设计了一个统一的程序开发模型,对于数据通信提供了最基本最有弹性的支持,这就是 Windows Communication Foundation。

编辑本段概念

  WCF 由于集合了几乎由 .NET Framework 所提供的通信方法,因此学习曲线比较陡峭,开发人员必须要针对各个部份的内涵做深入的了解,才能够操控 WCF 来开发应用程序

  通信双方的沟通方式,由合约来订定。通信双方所遵循的通信方法,由协议绑定来订定。通信期间的安全性,由双方约定的安全性层次来订定。

合约(Contract)

  WCF 的基本概念是以合约(Contract) 来定义双方沟通的协议,合约必须要以接口的方式来体现,而实际的服务代码必须要由这些合约接口派生并实现。合约分成了四种:

  数据合约 (Data Contract),订定双方沟通时的数据格式。服务合约 (Service Contract),订定服务的定义。操作合约 (Operation Contract),订定服务提供的方法。消息合约 (Message Contract),订定在通信期间改写消息内容的规范。一个 WCF 中的合约,就如同下列代码所示:

  using System;

  using System.ServiceModel;

  namespace Microsoft.ServiceModel.Samples{

  [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] // 服务合约

  public interface ICalculator

  {

  [OperationContract] // 操作合约

  double Add(double n1, double n2);

  [OperationContract] // 操作合约

  double Subtract(double n1, double n2);

  [OperationContract] // 操作合约

  double Multiply(double n1, double n2);

  [OperationContract] // 操作合约

  double Divide(double n1, double n2);

  }

  }

协议绑定 (Binding)

  由于 WCF 支持了 HTTPTCP,Named Pipe,MSMQ,Peer-To-Peer TCP 等协议,而 HTTP 又分为基本 HTTP 支持 (BasicHttpBinding) 以及 WS-HTTP 支持 (WsHttpBinding),而 TCP 亦支持 NetTcpBinding,NetPeerTcpBinding 等通信方式,因此,双方必须要统一通信的协议,并且也要在编码以及格式上要有所一致。

  一个设置通信协议绑定的示例如下:

  <?xml version="1.0" encoding="utf-8" ?>

  <configuration>

  <system.serviceModel>

  <!-- 设定服务系结的资讯 -->

  <services>

  <service name=" CalculatorService" >

  <endpoint address="" binding="wsHttpBinding" bindingConfiguration="Binding1" contract="ICalculator" />

  </service>

  </services>

  <!-- 设定通讯协定系结的资讯 -->

  <bindings>

  <wsHttpBinding>

  <binding name="Binding1">

  </binding>

  </wsHttpBinding>

  </bindings>

  </system.serviceModel>

  </configuration>

  虽然 WCF 也可以使用 SOAP做通信格式,但它和以往的 ASP.NETXML Web Services不同,因此有部分技术文章中,会将 ASP.NET 的 XML Web Services 称为 ASMX Service

  WCF 的服务可以挂载于 Console Application,Windows Application,IIS (ASP.NET) Application,Windows Service以及 Windows Activation Services中,但大多都会挂在 Windows Service。

安全性层次

  WCF 实现上已经支持了传输层次安全性 (Transport-level security) 以及消息层次安全性 (Message-level security) 两种。

  传输层次安全性:在数据传输时期加密,例如 SSL。消息层次安全性:在数据处理时就加密,例如使用数字签名,散列或是使用密钥加密法等。

编辑本段客户端

  对于 WCF 的客户端来说,WCF 服务就像是一个 Web Service 一样,在 Visual Studio 2008 中,所有 WCF 服务的连接都是由客户端的 服务代理(WCF Service Proxy) 来运行,开发人员不用花费太多心思在通信上,而 WCF Service Proxy 在 Visual Studio 中被称为服务引用(Service Reference)。

  在 Visual Studio 中加入 WCF 的服务参考时,Visual Studio 会自动帮开发人员做掉一些必要工作(例如组态创建以及产生 Service Proxy 等),开发人员只需要在代码中取用 WCF Service Proxy 对象即可。

编辑本段下载地址

  目前最新的WCF版本是February 2006 CTP,下载页面是:http://www.microsoft.com/downloads/details.aspx?FamilyId=F51C4D96-9AEA-474F-86D3-172BFA3B828B&displaylang=en。使用WCF需要用到一些相关的工具,如SvcUtil.exe,所以还需要下载WinFX Runtime Components的SDK,其下载页面是:http://www.microsoft.com/downloads/details.aspx?FamilyId=9BE1FC7F-0542-47F1-88DD-61E3EF88C402&displaylang=en。安装SDK可以选择网络安装或本地安装。如果是本地安装,文件大小为1.1G左右,是ISO文件。安装了SDK后,在program files目录下,有microsoft SDK目录。

  WCF是微软重点介绍的产品,因此也推出了专门的官方网站(http://windowscommunication.net),该网站有最新的WCF新闻发布,以及介绍WCF的技术文档和样例代码。

编辑本段WCF的优势

  在David Chappell所撰的《Introducing Windows Communication Foundation》一文中,用了一个活鲜鲜的例子,来说明WCF的优势所在。假定我们要为一家汽车租赁公司开发一个新的应用程序,用于租车预约服务。该租车预约服务会被多种应用程序访问,包括呼叫中心(Call Center),基于J2EE的租车预约服务以及合作伙伴的应用程序(Partner Application),如图所示:

  从功能的角度来看,WCF完全可以看作是ASMX,.Net Remoting,Enterprise Service,WSE,MSMQ等技术的并集。(注:这种说法仅仅是从功能的角度。事实上WCF远非简单的并集这样简单,它是真正面向服务的产品,它已经改变了通常的开发模式。)因此,对于上述汽车预约服务系统的例子,利用WCF,就可以解决包括安全、可信赖、互操作、跨平台通信等等需求。开发者再不用去分别了解.Net Remoting,ASMX等各种技术了。

  概括地说,WCF具有如下的优势:

  1、统一性

  前面已经叙述,WCF是对于ASMX,.Net Remoting,Enterprise Service,WSE,MSMQ等技术的整合。由于WCF完全是由托管代码编写,因此开发WCF的应用程序与开发其它的.Net应用程序没有太大的区别,我们仍然可以像创建面向对象的应用程序那样,利用WCF来创建面向服务的应用程序。http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf01.gif

  http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf03.gif

  2、互操作性

  由于WCF最基本的通信机制是SOAP(Simple Object Access Protocol 简易对象访问协议),这就保证了系统之间的互操作性,即使是运行不同的上下文中。这种通信可以是基于.Net到.Net间的通信,如下图所示:

  可以跨进程、跨机器甚至于跨平台的通信,只要支持标准的Web Service,例如J2EE应用服务器(如WebSphere,WebLogic)。应用程序可以运行在Windows操作系统下,也可以运行在其他的操作系统,如Sun Solaris,HP Unix,Linux等等。如下图所示:

  3、安全与可信赖

  WS-Security,WS-Trust和WS-SecureConversation均被添加到SOAP消息中,以用于用户认证,数据完整性验证,数据隐私等多种安全因素。

  在SOAP 的header中增加了WS-ReliableMessaging允许可信赖的端对端通信。而建立在WS-Coordination和WS- AtomicTransaction之上的基于SOAP格式交换的信息,则支持两阶段的事务提交(two-phase commit transactions)。http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf04.gif

  上述的多种WS-Policy在WCF中都给与了支持。对于Messaging而言,SOAP是Web Service的基本协议,它包含了消息头(header)和消息体(body)。在消息头中,定义了WS-Addressing用于定位SOAP消息的地址信息,同时还包含了MTOM(消息传输优化机制,Message Transmission Optimization Mechanism)。如图所示:http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf05.gif

  4、兼容性

  WCF充分的考虑到了与旧有系统的兼容性。安装WCF并不会影响原有的技术如ASMX和.Net Remoting。即使对于WCF和ASMX而言,虽然两者都使用了SOAP,但基于WCF开发的应用程序,仍然可以直接与ASMX进行交互。

编辑本段参考资料

  1.MSDN .NET Framework Developer Center: WCF

  2.MSDN Library: WCF Portal

  3.http://dotnet.blog.51cto.com/272325/52076

  本文中的示例均来自 MSDN Library: WCF Portal 中

扩展阅读:
开放分类:
visual studio 2005wcf

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值