這一系列文章的內容是從MSDN中COPY過來的,講述的是最簡單的WCF程序示例:如何在控制檯應用程序實現和承載WCF服務,以及如何建立、配置和使用WCF客戶端。編程
文章主體可分爲兩部分,分別介紹服務器端和客戶端的編程實現。細分的話,能夠分爲六項任務。服務器
這是建立基本 Windows Communication Foundation (WCF) 服務和可使用該服務的客戶端所需的六項任務中的第一項任務。app
建立基本 WCF 服務時,第一項任務是爲與外界共享的服務建立協定,並在其中描述如何與該服務進行通訊。ide
具體步驟爲: 工具
1、 建立新的控制檯應用程序項目。 在「新建項目」對話框中,選中「Visual Basic」或「Visual C#」,並選擇「控制檯應用程序」模板,並命名爲Service。 使用默認的位置。學習
2、將默認的Service 命名空間更改成 Microsoft.ServiceModel.Samples。spa
3、爲項目提供對 System.ServiceModel 命名空間的引用:右擊「解決方案資源管理器」中的「Service」項目,選擇「添加引用」項,在彈出的對話框中的「.NET」選項卡里的「組件名稱」中選擇「System.ServiceModel」,而後單擊「肯定」。命令行
下面是編程步驟:代理
1、爲 System.ServiceModel 命名空間添加一個 using 語句。 code
using System.ServiceModel;
2、建立一個新的ICalculator 接口,並將 ServiceContractAttribute 屬性應用於該接口,並將 Namespace 值設置爲「http://Microsoft.ServiceModel.Samples」。 此命名空間指定該服務在計算機上的路徑,並構成該服務的基址部分。 請注意,在經過採用方括號表示法的屬性來批註接口或類時,該屬性類能夠從其名稱中去掉「Attribute」部分。
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
3、在接口中建立方法聲明,並將 OperationContractAttribute 屬性應用於每一個要做爲公共 WCF 協定的一部分公開的方法。
[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);
下面是建立服務協定的完整代碼段:
using System;
// Add the using statement for the Sytem.ServiceModel namespace
using System.ServiceModel;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
// Create the method declaration for the contract.
[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);
}
}
........(整個服務器端的代碼未完,等講完任務三時,再給出完整代碼)
1、建立一個新 CalculatorService 類,該類從用戶定義的 ICalculator 接口繼承而來並實現該接口定義的協定功能。
public class CalculatorService : ICalculator
2、實現每一個算術運算符的功能。
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine("Received Add({0},{1})", n1, n2);
// Code added to write output to the console window.
Console.WriteLine("Return: {0}", result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 - n2;
Console.WriteLine("Received Subtract({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine("Received Multiply({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine("Received Divide({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
在建立和實現了服務協定後,下一步是運行該服務。 運行服務由三個步驟組成:配置、承載和打開服務。
爲服務的基址建立 Uri 實例。 此 URI 指定 HTTP 方案、本地計算機、端口號 8000,以及服務協定中爲服務命名空間指定的服務路徑ServiceModelSample/Services。
Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress); |
selfHost.AddServiceEndpoint( typeof(ICalculator), new WSHttpBinding(), "CalculatorService"); |
ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); |
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
下面是服務器端(即「Service」項目中program.cs文件中)的完整程序代碼:
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[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);
}
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine("Received Add({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 - n2;
Console.WriteLine("Received Subtract({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine("Received Multiply({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine("Received Divide({0},{1})", n1, n2);
Console.WriteLine("Return: {0}", result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// Create a URI to serve as the base address.
Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");
// Create ServiceHost
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
// Add a service endpoint.
selfHost.AddServiceEndpoint(
typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
// Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Start (and then stop) the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
}
若要運行服務,啓動項目文件夾下bin目錄中的 Service.exe便可。
前面三篇文章是講服務器端的部署和運行,下面講講客戶端如何配置和使用。
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
在 Visual Studio 中,將在前一過程當中生成的 App.config 配置文件添加到客戶端項目中。 在「解決方案資源管理器」中右擊該客戶端,選擇「添加現有項」,而後從 C:\Documents and Settings\<用戶名>\Documents\Visual Studio 2008\Projects\Service\Client\bin 目錄中選擇 App.config 配置文件。
將app.config添加到項目中後,就算是完成了wcf客戶端的配置。由於具體的配置信息,咱們在使用svcutil.exe工具時,它就幫咱們配置好並寫入了app.config文件。
1、爲要調用的服務的基址建立 EndpointAddress 實例,而後建立 WCF Client 對象。
//Create an endpoint address and an instance of the WCF Client.
EndpointAddress epAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service/CalculatorService");
CalculatorClient client = new CalculatorClient(new WSHttpBinding(), epAddress);
2、從 Client 內調用客戶端操做。
// Call the service operations.
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);
// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);
// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);
3、在 WCF 客戶端上調用 Close。
// Closing the client gracefully closes the connection and cleans up resources.
client.Close();
下面是客戶端的完整代碼:
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace ServiceModelSamples
{
class Client
{
static void Main()
{
//Step 1: Create an endpoint address and an instance of the WCF Client.
EndpointAddress epAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service/CalculatorService");
CalculatorClient client = new CalculatorClient(new WSHttpBinding(), epAddress);
// Step 2: Call the service operations.
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);
// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);
// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);
//Step 3: Closing the client gracefully closes the connection and cleans up resources.
client.Close();
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
}
}
若要啓動客戶端,請在「開始」菜單中的「Microsoft Windows SDK」項下選擇「CMD Shell」,從而啓動 Windows SDK 控制檯會話。 定位至 C:\Documents and Settings\<用戶名>\Documents\Visual Studio 2008\Projects\Service\Client\obj\Debug 目錄,鍵入 client,而後按Enter。 操做請求和響應將出如今客戶端控制檯窗口中,以下所示。
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Press <ENTER> to terminate client.
最後,附上個人ASP.NET學習羣,歡迎各位同行入羣指導交流。技術羣:【.NET技術社區】960640092
更多文章能夠關注博主我的站點:IT技術小趣屋。博主公衆號以下: