?http://www.dotblogs.com.tw/puma/archive/2009/06/21/wcf-net-tcp-channelfactory-clientbase.aspx
最近很少在寫文章,也佷少在討論區(qū)解問題(因為工作很忙),所以沒什麼東西可以寫
這幾天無聊去看看WCF的東西,介紹給大家如何利用net.tcp傳輸協(xié)定來建置WCF Service
啓動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 端啓動服務(wù)利用ServiceHost Client 端呼叫服務(wù)利用ClientBase 或ChannelFactory
此範(fàn)例主要是利用Console來啓動WCF Service,利用WinForm來呼叫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後就會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後就會Open Channel
51 ????????????//??? MessageBox.Show(client.HelloWorld());
HelloClient.cs
view source print?
02 using System.Collections.Generic;
06 namespace WinFormClient
09 ????/// 利用此類別來呼叫WCF Service,
11 ????publicclass HelloClient : System.ServiceModel.ClientBase<WcfBase.IHello>, WcfBase.IHello
13 ????????//沒有傳入任何Binding與EndpointAddress,會找App.Config的設(shè)定
14 ????????publicHelloClient()
19 ????????//依使用者定義的Binding與EndpointAddress,來設(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
不費話了,小弟先行謝過,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的解釋為“定義出站請求的行為和客戶端應(yīng)用程序使用的請求/答復(fù)通道。”,這里應(yīng)該是建立通道的方法的實現(xiàn)的接口了? 能不能擴(kuò)展說下通道是怎樣建立的,滿足下小弟的求知欲。。。 } [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); 這里就是調(diào)用服務(wù)器端的方法嘍。。。 ? } ? ? ? public void HelloWorld(string name) ? { ? base.Channel.HelloWorld(name); ? } } 問題七:這些“【】”里的都是些神馬東西,如果把它們?nèi)チ?#xff0c;對程序的運行影響大嗎???
?
=============
http://baike.baidu.com/view/1140438.htm
概述 Windows Communication Foundation(WCF) 是由微軟發(fā)展的一組數(shù)據(jù)通信的應(yīng)用程序開發(fā)接口 可以翻譯為Windows通訊接口,它是.NET框架的一部分,由 .NET Framework 3.0 開始引入,與 Windows Presentation Foundation及 Windows Workflow Foundation并行為新一代 Windows 操作系統(tǒng)以及 WinFX 的三個重大應(yīng)用程序開發(fā)類庫。在 .NET Framework 2.0 以及前版本中,微軟發(fā)展了 Web Service (SOAP with HTTP communication),.NET Remoting (TCP/HTTP/Pipeline communication) 以及基礎(chǔ)的 Winsock 等通信支持,由于各個通信方法的設(shè)計方法不同,而且彼此之間也有相互的重疊性(例如 .NET Remoting 可以開發(fā) SOAP, HTTP 通信),對于開發(fā)人員來說,不同的選擇會有不同的程序設(shè)計模型,而且必須要重新學(xué)習(xí),讓開發(fā)人員在使用中有許多不便。同時,面向服務(wù)架構(gòu) (Service-Oriented Architecture) 也開始盛行于軟件工業(yè)中,因此微軟重新查看了這些通信方法,并設(shè)計了一個統(tǒng)一的程序開發(fā)模型,對于數(shù)據(jù)通信提供了最基本最有彈性的支持,這就是 Windows Communication Foundation。
編輯本段 概念
WCF 由于集合了幾乎由 .NET Framework 所提供的通信方法,因此學(xué)習(xí)曲線比較陡峭,開發(fā)人員必須要針對各個部份的內(nèi)涵做深入的了解,才能夠操控 WCF 來開發(fā)應(yīng)用程序。
通信雙方的溝通方式,由合約來訂定。通信雙方所遵循的通信方法,由協(xié)議綁定來訂定。通信期間的安全性,由雙方約定的安全性層次來訂定。
合約(Contract)
WCF 的基本概念是以合約(Contract) 來定義雙方溝通的協(xié)議,合約必須要以接口的方式來體現(xiàn),而實際的服務(wù)代碼必須要由這些合約接口派生并實現(xiàn)。合約分成了四種:
數(shù)據(jù)合約 (Data Contract),訂定雙方溝通時的數(shù)據(jù)格式。服務(wù)合約 (Service Contract),訂定服務(wù)的定義。操作合約 (Operation Contract),訂定服務(wù)提供的方法。消息合約 (Message Contract),訂定在通信期間改寫消息內(nèi)容的規(guī)范。一個 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é)議,并且也要在編碼以及格式上要有所一致。
一個設(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ù)文章中,會將 ASP.NET 的 XML Web Services 稱為 ASMX Service 。
WCF 的服務(wù)可以掛載于 Console Application,Windows Application,IIS (ASP.NET) Application,Windows Service以及 Windows Activation Services中,但大多都會掛在 Windows Service。
安全性層次
WCF 實現(xiàn)上已經(jīng)支持了傳輸層次安全性 (Transport-level security) 以及消息層次安全性 (Message-level security) 兩種。
傳輸層次安全性:在數(shù)據(jù)傳輸時期加密,例如 SSL。消息層次安全性:在數(shù)據(jù)處理時就加密,例如使用數(shù)字簽名,散列或是使用密鑰加密法等。
編輯本段 客戶端
對于 WCF 的客戶端來說,WCF 服務(wù)就像是一個 Web Service 一樣,在 Visual Studio 2008 中,所有 WCF 服務(wù)的連接都是由客戶端的 服務(wù)代理(WCF Service Proxy ) 來運行,開發(fā)人員不用花費太多心思在通信上,而 WCF Service Proxy 在 Visual Studio 中被稱為服務(wù)引用 (Service Reference)。
在 Visual Studio 中加入 WCF 的服務(wù)參考時,Visual Studio 會自動幫開發(fā)人員做掉一些必要工作(例如組態(tài)創(chuàng)建以及產(chǎn)生 Service Proxy 等),開發(fā)人員只需要在代碼中取用 WCF Service Proxy 對象即可。
編輯本段 下載地址
目前最新的WCF版本是February 2006 CTP,下載頁面是:http://www.microsoft.com/downloads/details.aspx?FamilyId=F51C4D96-9AEA-474F-86D3-172BFA3B828B&displaylang=en。使用WCF需要用到一些相關(guān)的工具,如SvcUtil.exe,所以還需要下載WinFX Runtime Components的SDK,其下載頁面是: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是微軟重點介紹的產(chǎn)品,因此也推出了專門的官方網(wǎng)站(http://windowscommunication.net),該網(wǎng)站有最新的WCF新聞發(fā)布,以及介紹WCF的技術(shù)文檔和樣例代碼。
編輯本段 WCF的優(yōu)勢
在David Chappell所撰的《Introducing Windows Communication Foundation》一文中,用了一個活鮮鮮的例子,來說明WCF的優(yōu)勢所在。假定我們要為一家汽車租賃公司開發(fā)一個新的應(yīng)用程序,用于租車預(yù)約服務(wù)。該租車預(yù)約服務(wù)會被多種應(yīng)用程序訪問,包括呼叫中心(Call Center),基于J2EE的租車預(yù)約服務(wù)以及合作伙伴的應(yīng)用程序(Partner Application),如圖所示:
從功能的角度來看,WCF完全可以看作是ASMX,.Net Remoting,Enterprise Service,WSE,MSMQ等技術(shù)的并集。(注:這種說法僅僅是從功能的角度。事實上WCF遠(yuǎn)非簡單的并集這樣簡單,它是真正面向服務(wù)的產(chǎn)品,它已經(jīng)改變了通常的開發(fā)模式。)因此,對于上述汽車預(yù)約服務(wù)系統(tǒng)的例子,利用WCF,就可以解決包括安全、可信賴、互操作、跨平臺通信等等需求。開發(fā)者再不用去分別了解.Net Remoting,ASMX等各種技術(shù)了。
概括地說,WCF具有如下的優(yōu)勢:
1、統(tǒng)一性
前面已經(jīng)敘述,WCF是對于ASMX,.Net Remoting,Enterprise Service,WSE,MSMQ等技術(shù)的整合。由于WCF完全是由托管代碼編寫,因此開發(fā)WCF的應(yīng)用程序與開發(fā)其它的.Net應(yīng)用程序沒有太大的區(qū)別,我們?nèi)匀豢梢韵駝?chuàng)建面向?qū)ο蟮膽?yīng)用程序那樣,利用WCF來創(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 簡易對象訪問協(xié)議),這就保證了系統(tǒng)之間的互操作性,即使是運行不同的上下文中。這種通信可以是基于.Net到.Net間的通信,如下圖所示:
可以跨進(jìn)程、跨機(jī)器甚至于跨平臺的通信,只要支持標(biāo)準(zhǔn)的Web Service,例如J2EE應(yīng)用服務(wù)器(如WebSphere,WebLogic)。應(yīng)用程序可以運行在Windows操作系統(tǒng)下,也可以運行在其他的操作系統(tǒng),如Sun Solaris,HP Unix,Linux等等。如下圖所示:
3、安全與可信賴
WS-Security,WS-Trust和WS-SecureConversation均被添加到SOAP消息中,以用于用戶認(rèn)證,數(shù)據(jù)完整性驗證,數(shù)據(jù)隱私等多種安全因素。
在SOAP 的header中增加了WS-ReliableMessaging允許可信賴的端對端通信。而建立在WS-Coordination和WS- AtomicTransaction之上的基于SOAP格式交換的信息,則支持兩階段的事務(wù)提交(two-phase commit transactions)。http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf04.gif
上述的多種WS-Policy在WCF中都給與了支持。對于Messaging而言,SOAP是Web Service的基本協(xié)議,它包含了消息頭(header)和消息體(body)。在消息頭中,定義了WS-Addressing用于定位SOAP消息的地址信息,同時還包含了MTOM(消息傳輸優(yōu)化機(jī)制,Message Transmission Optimization Mechanism)。如圖所示:http://wayfarer.cnblogs.com/images/cnblogs_com/wayfarer/wcf/wcf05.gif
4、兼容性
WCF充分的考慮到了與舊有系統(tǒng)的兼容性。安裝WCF并不會影響原有的技術(shù)如ASMX和.Net Remoting。即使對于WCF和ASMX而言,雖然兩者都使用了SOAP,但基于WCF開發(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
本文中的示例均來自 MSDN Library: WCF Portal 中
擴(kuò)展閱讀:
開放分類:
visual studio 2005,wcf
?
總結(jié)
以上是生活随笔 為你收集整理的[WCF]利用net.tcp傳輸協定來建置WCF Service 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔 推薦給好友。