?http://www.dotblogs.com.tw/puma/archive/2009/06/21/wcf-net-tcp-channelfactory-clientbase.aspx
最近很少在寫(xiě)文章,也佷少在討論區(qū)解問(wèn)題(因?yàn)楣ぷ骱苊?,所以沒(méi)什麼東西可以寫(xiě)
這幾天無(wú)聊去看看WCF的東西,介紹給大家如何利用net.tcp傳輸協(xié)定來(lái)建置WCF Service
啓動(dòng)WCF服務(wù)的方式有下列幾種方式:
1.利用Console或WinFrom方式 2.利用Windows Service方式 3.利用Web Server IIS方式
WCF支援的傳輸協(xié)定有下列幾種方式:
1.HTTP 2.net.tcp 3.net.pipe 4.net.msmq
存取WCF服務(wù)的Client端也可利用下列幾種方式:
1.WinForm or Console 2.ASP.NET or ASP.NET AJAX 3.WPF or Silverlight ...很多
首先準(zhǔn)備下列專案:
WcfBase 是給ConsoleHost 與WinFormClient 共用的 ConsoleHost 是Server 端 WinFormClient 是Client 端
Server 端啓動(dòng)服務(wù)利用ServiceHost Client 端呼叫服務(wù)利用ClientBase 或ChannelFactory
此範(fàn)例主要是利用Console來(lái)啓動(dòng)WCF Service,利用WinForm來(lái)呼叫WCF Service
WcfBase(IHello.cs,Hello.cs)
IHello.cs
view source print?
02 using System.Collections.Generic;
05 using System.ServiceModel;
06 //加入System.ServiceModel參考
11 ????publicinterface IHello
13 ????????[OperationContract]
14 ????????stringHelloWorld();
Hello.cs
view source print?
02 using System.Collections.Generic;
08 ????publicclass Hello : IHello
10 ????????publicstring HelloWorld()
12 ????????????return"HelloWorld";
ConsoleHost(Program.cs,App.config)
Program.cs
view source print?
02 using System.Collections.Generic;
05 using System.ServiceModel;
06 //加入System.ServiceModel與WcfBase參考
12 ????????staticvoid Main(string[] args)
14 ????????????//WCF Console Host
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();
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();
App.config
view source print?
01 <?xmlversion="1.0"encoding="utf-8"?>
03 ??<system.serviceModel>
05 ??????<servicename="WcfBase.Hello">
06 ????????<endpointaddress="HelloService"binding="netTcpBinding"contract="WcfBase.IHello"/>
08 ??????????<baseAddresses>
09 ????????????<addbaseAddress="net.tcp://localhost:9000/"/>
10 ??????????</baseAddresses>
14 ??</system.serviceModel>
WinFormClient(FrmClient.cs,HelloClient.cs,App.config)
FrmClient.cs
view source print?
02 using System.Collections.Generic;
03 using System.ComponentModel;
08 using System.Windows.Forms;
09 using System.ServiceModel;
10 //加入System.ServiceModel與WcfBase參考
12 namespace WinFormClient
14 ????publicpartial classFrmClient : Form
16 ????????publicFrmClient()
18 ????????????InitializeComponent();
21 ????????privatevoid btnClientBase_Click(objectsender, EventArgs e)
23 ????????????//此種方式需App.Config
24 ????????????using(HelloClient client = newHelloClient())
26 ????????????????client.Open();
27 ????????????????MessageBox.Show(client.HelloWorld());
30 ????????????//此種方式不需App.Config
31 ????????????//using (HelloClient client = new HelloClient( new NetTcpBinding(),new EndpointAddress("net.tcp://localhost:9000/HelloService")))
33 ????????????//??? client.Open();
34 ????????????//??? MessageBox.Show(client.HelloWorld());
38 ????????privatevoid btnChannelFactory_Click(objectsender, EventArgs e)
40 ????????????//此種方式需App.Config
41 ????????????using(ChannelFactory<WcfBase.IHello> channel = newChannelFactory<WcfBase.IHello>("Hello"))//指定ConfigName
43 ????????????????WcfBase.IHello client = channel.CreateChannel();//CreateChannel後就會(huì)Open Channel
44 ????????????????MessageBox.Show(client.HelloWorld());
47 ????????????//此種方式不需App.Config
48 ????????????//using (ChannelFactory<WcfBase.IHello> channel = new ChannelFactory<WcfBase.IHello>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/HelloService")))
50 ????????????//??? WcfBase.IHello client = channel.CreateChannel();//CreateChannel後就會(huì)Open Channel
51 ????????????//??? MessageBox.Show(client.HelloWorld());
HelloClient.cs
view source print?
02 using System.Collections.Generic;
06 namespace WinFormClient
09 ????/// 利用此類別來(lái)呼叫WCF Service,
11 ????publicclass HelloClient : System.ServiceModel.ClientBase<WcfBase.IHello>, WcfBase.IHello
13 ????????//沒(méi)有傳入任何Binding與EndpointAddress,會(huì)找App.Config的設(shè)定
14 ????????publicHelloClient()
19 ????????//依使用者定義的Binding與EndpointAddress,來(lái)設(shè)定
20 ????????publicHelloClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)
21 ????????????:base(binding, remoteAddress)
26 ????????publicstring HelloWorld()
28 ????????????returnbase.Channel.HelloWorld();
App.config
view source print?
1 <?xmlversion="1.0"encoding="utf-8"?>
5 ??????<endpointname="Hello"address="net.tcp://localhost:9000/HelloService"binding="netTcpBinding"contract="WcfBase.IHello">
8 ??</system.serviceModel>
設(shè)定Config可以利用SvcConfigEditor.exe工具
參考網(wǎng)址: 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
不費(fèi)話了,小弟先行謝過(guò),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> //------------------------------------------------------------------------------ 問(wèn)題一:這里的注釋的意思是,代碼是有工具生成的,神馬意思?這種代碼可以使用工具生成? [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="CalculatorHello")] 問(wèn)題二:這兩句神馬意思?有有神馬作用? public interface CalculatorHello { ? ? ? [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/CalculatorHello/Add", ReplyAction="http://tempuri.org/CalculatorHello/AddResponse")] 問(wèn)題三:這里的又是神馬意思?有神嗎作用? ? 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 { 問(wèn)題四:MSDN的解釋為“定義出站請(qǐng)求的行為和客戶端應(yīng)用程序使用的請(qǐng)求/答復(fù)通道?!?#xff0c;這里應(yīng)該是建立通道的方法的實(shí)現(xiàn)的接口了? 能不能擴(kuò)展說(shuō)下通道是怎樣建立的,滿足下小弟的求知欲。。。 } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] public partial class CalculatorHelloClient : System.ServiceModel.ClientBase<CalculatorHello>, CalculatorHello { 問(wèn)題五:System.ServiceModel.ClientBase<CalculatorHello>是什么?有神嗎作用? ? ? ? public CalculatorHelloClient() ? { ? } ? ? ? public CalculatorHelloClient(string endpointConfigurationName) :? ? base(endpointConfigurationName) 問(wèn)題六:這個(gè)方法是干嘛使得?“base”MSDN上沒(méi)找著啊???有神嗎作用??? ? { ? } ? ? ? 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); 這里就是調(diào)用服務(wù)器端的方法嘍。。。 ? } ? ? ? public void HelloWorld(string name) ? { ? base.Channel.HelloWorld(name); ? } } 問(wèn)題七:這些“【】”里的都是些神馬東西,如果把它們?nèi)チ?#xff0c;對(duì)程序的運(yùn)行影響大嗎???
?
=============
http://baike.baidu.com/view/1140438.htm
概述 Windows Communication Foundation(WCF) 是由微軟發(fā)展的一組數(shù)據(jù)通信的應(yīng)用程序開(kāi)發(fā)接口 可以翻譯為Windows通訊接口,它是.NET框架的一部分,由 .NET Framework 3.0 開(kāi)始引入,與 Windows Presentation Foundation及 Windows Workflow Foundation并行為新一代 Windows 操作系統(tǒng)以及 WinFX 的三個(gè)重大應(yīng)用程序開(kāi)發(fā)類庫(kù)。在 .NET Framework 2.0 以及前版本中,微軟發(fā)展了 Web Service (SOAP with HTTP communication),.NET Remoting (TCP/HTTP/Pipeline communication) 以及基礎(chǔ)的 Winsock 等通信支持,由于各個(gè)通信方法的設(shè)計(jì)方法不同,而且彼此之間也有相互的重疊性(例如 .NET Remoting 可以開(kāi)發(fā) SOAP, HTTP 通信),對(duì)于開(kāi)發(fā)人員來(lái)說(shuō),不同的選擇會(huì)有不同的程序設(shè)計(jì)模型,而且必須要重新學(xué)習(xí),讓開(kāi)發(fā)人員在使用中有許多不便。同時(shí),面向服務(wù)架構(gòu) (Service-Oriented Architecture) 也開(kāi)始盛行于軟件工業(yè)中,因此微軟重新查看了這些通信方法,并設(shè)計(jì)了一個(gè)統(tǒng)一的程序開(kāi)發(fā)模型,對(duì)于數(shù)據(jù)通信提供了最基本最有彈性的支持,這就是 Windows Communication Foundation。
編輯本段 概念
WCF 由于集合了幾乎由 .NET Framework 所提供的通信方法,因此學(xué)習(xí)曲線比較陡峭,開(kāi)發(fā)人員必須要針對(duì)各個(gè)部份的內(nèi)涵做深入的了解,才能夠操控 WCF 來(lái)開(kāi)發(fā)應(yīng)用程序。
通信雙方的溝通方式,由合約來(lái)訂定。通信雙方所遵循的通信方法,由協(xié)議綁定來(lái)訂定。通信期間的安全性,由雙方約定的安全性層次來(lái)訂定。
合約(Contract)
WCF 的基本概念是以合約(Contract) 來(lái)定義雙方溝通的協(xié)議,合約必須要以接口的方式來(lái)體現(xiàn),而實(shí)際的服務(wù)代碼必須要由這些合約接口派生并實(shí)現(xiàn)。合約分成了四種:
數(shù)據(jù)合約 (Data Contract),訂定雙方溝通時(shí)的數(shù)據(jù)格式。服務(wù)合約 (Service Contract),訂定服務(wù)的定義。操作合約 (Operation Contract),訂定服務(wù)提供的方法。消息合約 (Message Contract),訂定在通信期間改寫(xiě)消息內(nèi)容的規(guī)范。一個(gè) WCF 中的合約,就如同下列代碼所示:
using System;
using System.ServiceModel;
namespace Microsoft.ServiceModel.Samples{
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] // 服務(wù)合約
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);
}
}
協(xié)議綁定 (Binding)
由于 WCF 支持了 HTTP,TCP,Named Pipe,MSMQ,Peer-To-Peer TCP 等協(xié)議,而 HTTP 又分為基本 HTTP 支持 (BasicHttpBinding) 以及 WS-HTTP 支持 (WsHttpBinding),而 TCP 亦支持 NetTcpBinding,NetPeerTcpBinding 等通信方式,因此,雙方必須要統(tǒng)一通信的協(xié)議,并且也要在編碼以及格式上要有所一致。
一個(gè)設(shè)置通信協(xié)議綁定的示例如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<!-- 設(shè)定服務(wù)系結(jié)的資訊 -->
<services>
<service name=" CalculatorService" >
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="Binding1" contract="ICalculator" />
</service>
</services>
<!-- 設(shè)定通訊協(xié)定系結(jié)的資訊 -->
<bindings>
<wsHttpBinding>
<binding name="Binding1">
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
雖然 WCF 也可以使用 SOAP做通信格式,但它和以往的 ASP.NETXML Web Services不同,因此有部分技術(shù)文章中,會(huì)將 ASP.NET 的 XML Web Services 稱為 ASMX Service 。
WCF 的服務(wù)可以掛載于 Console Application,Windows Application,IIS (ASP.NET) Application,Windows Service以及 Windows Activation Services中,但大多都會(huì)掛在 Windows Service。
安全性層次
WCF 實(shí)現(xiàn)上已經(jīng)支持了傳輸層次安全性 (Transport-level security) 以及消息層次安全性 (Message-level security) 兩種。
傳輸層次安全性:在數(shù)據(jù)傳輸時(shí)期加密,例如 SSL。消息層次安全性:在數(shù)據(jù)處理時(shí)就加密,例如使用數(shù)字簽名,散列或是使用密鑰加密法等。
編輯本段 客戶端
對(duì)于 WCF 的客戶端來(lái)說(shuō),WCF 服務(wù)就像是一個(gè) Web Service 一樣,在 Visual Studio 2008 中,所有 WCF 服務(wù)的連接都是由客戶端的 服務(wù)代理(WCF Service Proxy ) 來(lái)運(yùn)行,開(kāi)發(fā)人員不用花費(fèi)太多心思在通信上,而 WCF Service Proxy 在 Visual Studio 中被稱為服務(wù)引用 (Service Reference)。
在 Visual Studio 中加入 WCF 的服務(wù)參考時(shí),Visual Studio 會(huì)自動(dòng)幫開(kāi)發(fā)人員做掉一些必要工作(例如組態(tài)創(chuàng)建以及產(chǎn)生 Service Proxy 等),開(kāi)發(fā)人員只需要在代碼中取用 WCF Service Proxy 對(duì)象即可。
編輯本段 下載地址
目前最新的WCF版本是February 2006 CTP,下載頁(yè)面是:http://www.microsoft.com/downloads/details.aspx?FamilyId=F51C4D96-9AEA-474F-86D3-172BFA3B828B&displaylang=en。使用WCF需要用到一些相關(guān)的工具,如SvcUtil.exe,所以還需要下載WinFX Runtime Components的SDK,其下載頁(yè)面是:http://www.microsoft.com/downloads/details.aspx?FamilyId=9BE1FC7F-0542-47F1-88DD-61E3EF88C402&displaylang=en。安裝SDK可以選擇網(wǎng)絡(luò)安裝或本地安裝。如果是本地安裝,文件大小為1.1G左右,是ISO文件。安裝了SDK后,在program files目錄下,有microsoft SDK目錄。
WCF是微軟重點(diǎn)介紹的產(chǎn)品,因此也推出了專門(mén)的官方網(wǎng)站(http://windowscommunication.net),該網(wǎng)站有最新的WCF新聞發(fā)布,以及介紹WCF的技術(shù)文檔和樣例代碼。
編輯本段 WCF的優(yōu)勢(shì)
在David Chappell所撰的《Introducing Windows Communication Foundation》一文中,用了一個(gè)活鮮鮮的例子,來(lái)說(shuō)明WCF的優(yōu)勢(shì)所在。假定我們要為一家汽車(chē)租賃公司開(kāi)發(fā)一個(gè)新的應(yīng)用程序,用于租車(chē)預(yù)約服務(wù)。該租車(chē)預(yù)約服務(wù)會(huì)被多種應(yīng)用程序訪問(wèn),包括呼叫中心(Call Center),基于J2EE的租車(chē)預(yù)約服務(wù)以及合作伙伴的應(yīng)用程序(Partner Application),如圖所示:
從功能的角度來(lái)看,WCF完全可以看作是ASMX,.Net Remoting,Enterprise Service,WSE,MSMQ等技術(shù)的并集。(注:這種說(shuō)法僅僅是從功能的角度。事實(shí)上WCF遠(yuǎn)非簡(jiǎn)單的并集這樣簡(jiǎn)單,它是真正面向服務(wù)的產(chǎn)品,它已經(jīng)改變了通常的開(kāi)發(fā)模式。)因此,對(duì)于上述汽車(chē)預(yù)約服務(wù)系統(tǒng)的例子,利用WCF,就可以解決包括安全、可信賴、互操作、跨平臺(tái)通信等等需求。開(kāi)發(fā)者再不用去分別了解.Net Remoting,ASMX等各種技術(shù)了。
概括地說(shuō),WCF具有如下的優(yōu)勢(shì):
1、統(tǒng)一性
前面已經(jīng)敘述,WCF是對(duì)于ASMX,.Net Remoting,Enterprise Service,WSE,MSMQ等技術(shù)的整合。由于WCF完全是由托管代碼編寫(xiě),因此開(kāi)發(fā)WCF的應(yīng)用程序與開(kāi)發(fā)其它的.Net應(yīng)用程序沒(méi)有太大的區(qū)別,我們?nèi)匀豢梢韵駝?chuàng)建面向?qū)ο蟮膽?yīng)用程序那樣,利用WCF來(lái)創(chuàng)建面向服務(wù)的應(yīng)用程序。http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf01.gif
http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf03.gif
2、互操作性
由于WCF最基本的通信機(jī)制是SOAP(Simple Object Access Protocol 簡(jiǎn)易對(duì)象訪問(wèn)協(xié)議),這就保證了系統(tǒng)之間的互操作性,即使是運(yùn)行不同的上下文中。這種通信可以是基于.Net到.Net間的通信,如下圖所示:
可以跨進(jìn)程、跨機(jī)器甚至于跨平臺(tái)的通信,只要支持標(biāo)準(zhǔn)的Web Service,例如J2EE應(yīng)用服務(wù)器(如WebSphere,WebLogic)。應(yīng)用程序可以運(yùn)行在Windows操作系統(tǒng)下,也可以運(yùn)行在其他的操作系統(tǒng),如Sun Solaris,HP Unix,Linux等等。如下圖所示:
3、安全與可信賴
WS-Security,WS-Trust和WS-SecureConversation均被添加到SOAP消息中,以用于用戶認(rèn)證,數(shù)據(jù)完整性驗(yàn)證,數(shù)據(jù)隱私等多種安全因素。
在SOAP 的header中增加了WS-ReliableMessaging允許可信賴的端對(duì)端通信。而建立在WS-Coordination和WS- AtomicTransaction之上的基于SOAP格式交換的信息,則支持兩階段的事務(wù)提交(two-phase commit transactions)。http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf04.gif
上述的多種WS-Policy在WCF中都給與了支持。對(duì)于Messaging而言,SOAP是Web Service的基本協(xié)議,它包含了消息頭(header)和消息體(body)。在消息頭中,定義了WS-Addressing用于定位SOAP消息的地址信息,同時(shí)還包含了MTOM(消息傳輸優(yōu)化機(jī)制,Message Transmission Optimization Mechanism)。如圖所示:http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf05.gif
4、兼容性
WCF充分的考慮到了與舊有系統(tǒng)的兼容性。安裝WCF并不會(huì)影響原有的技術(shù)如ASMX和.Net Remoting。即使對(duì)于WCF和ASMX而言,雖然兩者都使用了SOAP,但基于WCF開(kāi)發(fā)的應(yīng)用程序,仍然可以直接與ASMX進(jìn)行交互。
編輯本段 參考資料
1.MSDN .NET Framework Developer Center: WCF
2.MSDN Library: WCF Portal
3.http://dotnet.blog.51cto.com/272325/52076
本文中的示例均來(lái)自 MSDN Library: WCF Portal 中
擴(kuò)展閱讀:
開(kāi)放分類:
visual studio 2005,wcf
?
總結(jié)
以上是生活随笔 為你收集整理的[WCF]利用net.tcp傳輸協定來建置WCF Service 的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。