65.9K
CodeProject 正在变化。 阅读更多。
Home

WCF: 快速游览

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.77/5 (21投票s)

2008年7月21日

CPOL

3分钟阅读

viewsIcon

32420

downloadIcon

272

简要说明如何使用 WCF 创建一个小型完整的应用程序

BankSystem

引言

今天我将介绍一项名为 WCF(即“Windows Communication Foundation”)的新技术。 在深入探讨细节之前,让我们先定义一下问题。 我们有多个程序(服务器和客户端)需要通信才能完成其目标。

例如,如果我们需要创建一个聊天系统,我们可以通过客户端服务器方式实现。服务器将负责接收来自聊天客户端的请求(例如登录请求、发送消息请求、注销请求……),而客户端将被视为瘦客户端,因为大多数操作都在服务器端完成。 这是一个我们需要通信框架的常见示例。

另一个例子是开发需要大量处理的程序。 我们建议在功能强大的机器上放置服务器应用程序,而在简单的机器上放置任何简单的客户端应用程序,例如笔记本电脑。 小型 PC 可以连接到服务器并使用它。

这只是通过说明我们需要此技术的场景的介绍。 让我们看看当前的实现可能性,即我们可用于实现它的技术。

背景

最流行的技术是:COM、COM+、CORBA 和 WCF。 COM 和 COM+ 使用 C++ 语言实现,但由于使用了指针,因此对于许多开发人员来说,它被认为非常困难。 对于 CORBA,它是用 Java 实现的,我用过它,我认为它很简单并且具有一个重要的特性,即跨平台。 我稍后会尝试发布一篇关于如何使用它的文章。

Using the Code

我将带您了解一个由 WCF 和 C# 实现的小应用程序(客户端和服务器)。 此应用程序的目的是模拟一个非常小的银行系统,如下所示

服务器必须提供以下功能

  • AddAccount
  • RemoveAccount
  • GetAccounts

客户端将负责从服务器调用前面的功能。 这是我们的步骤。

服务器端

  1. 在 C# 语言中创建一个新的控制台应用程序,并将 *System.ServiceModel.dll* 添加到其引用,方法是导航到此路径 “*c:\windows\Microsoft.Net\Framework\v3.0\Windows Communication Foundation*”,然后选择 *system.servicemodel.dll*。

  2. 创建我们的契约:契约是一个接口,其中包含服务器将来会实现的功能 :D。 我们可以将其定义为:向您的应用程序添加一个新类,并将此代码粘贴到其中

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    
    namespace BankServer
    {
        [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
        public interface IBank
        {
            [OperationContract]
            int AddAccount(string clientName, int clientAge);
            [OperationContract]
            bool RemoveAccount(int accountNumber);
            [OperationContract]
            List<String> GetAccounts();
        }
    }
  3. 创建我们的数据模型,即 Account 类。 添加一个新类,将其命名为 Account 并粘贴此代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace BankServer
    {
        class Account
        {
            private int _id = 0;
            private string _name = "";
            private int _age = 0;
            public Account(int id, string name, int age)
            {
                _id = id;
                _name = name;
                _age = age;
            }
            public string ClientName
            {
                get { return _name; }
                set { _name = value; }
            }
            public int ClientAge
            {
                get { return _age; }
                set { _age = value; }
            }
            public int ID
            {
                get { return _id; }
                set { _id = value; }
            }
            public override string ToString()
            {
                return String.Format("ID:{0} Name:{1} Age:{2}",
    			_id.ToString(), _name, _age.ToString());
            }
            public override bool Equals(object obj)
            {
                Account temp = (Account)obj;
                return this.ID.Equals(temp.ID);        
    	}  
        }
    }
  4. 实现契约:创建一个名为 bank 的新类,并将此代码放入其中

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace BankServer
    {
        class Bank :IBank
        {
            private List<Account> _accounts = new List<Account>();
            private int _idGenerator = 0;
    
            public int AddAccount(string clientName, int clientAge)
            {
                _idGenerator++;
                Account acc = new Account(_idGenerator, clientName, clientAge);
                _accounts.Add(acc);
                return _idGenerator;
            }
    
            public bool RemoveAccount(int accountNumber)
            {
                Account acc = new Account(accountNumber, "", 0);
                return _accounts.Remove(acc);
            }
    
            public List<string> GetAccounts()
            {
                List<string> accLst = new List<string>();
                foreach (Account acc in _accounts)
                {
                    accLst.Add(acc.ToString());
                }
                return accLst;
            }
        }
    }
  5. 配置服务器:这将指定我们服务的地址并启动它。 将此代码复制并粘贴到 *program.cs* 中

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    namespace BankServer
    {
        class Program
        {
            static void Main(string[] args)
            {
                Uri baseAddress = new Uri
    		("https://:8000/ServiceModelSamples/Services");
    
                ServiceHost selfHost = new ServiceHost(typeof(Bank), baseAddress);
    
                try
                {
                    //configure the service.
                    selfHost.AddServiceEndpoint(typeof(IBank), 
    				new WSHttpBinding(), "BankService");
    
                    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    selfHost.Description.Behaviors.Add(smb);
    
                    //start the service.
                    selfHost.Open();
                    Console.WriteLine("Our Bank Service is Open now");
                    Console.WriteLine("Press <ENTER> to close it");
                    Console.WriteLine();
                    Console.ReadLine();
    
                    selfHost.Close();
                }
                catch (CommunicationException cs)
                {
                    Console.WriteLine("Exception:{0}", cs.Message);
                    selfHost.Abort();
                }
            }
        }
    }

客户端

  1. 创建您的客户端:右键单击您的解决方案并创建一个新项目。 将其命名为 MyBankClient,其类型为控制台 C# 应用程序,并且不要忘记添加 *System.ServiceModel.dll*。 您可以在“最近”选项卡中找到它。

  2. 在客户端中生成一个代理类,您将使用它来处理 bankservice

    • 启动您的服务器。
    • 打开 Visual Studio 2008 命令提示符。
    • 导航到您的客户端文件夹。
    • 写入此命令

      svcutil.exe /language:cs /out:generatedProxy.cs 
          /config:app.conig https://:8000/ServiceModelSamples/services
    • 这将生成两个文件:一个代理类和一个配置文件。
    • 右键单击您的客户端项目并添加现有项,然后选择 *generatedProxy.cs*。
  3. 使用我们的银行服务。 将此代码粘贴到您的 *program.cs* 中

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    
    namespace MyBankClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                EndpointAddress epAddress = new EndpointAddress
    	    ("https://:8000/ServiceModelSamples/Services/BankService");
                BankClient client = new BankClient(new WSHttpBinding(), epAddress);
    
                Console.WriteLine("Adding John , 20 years");
                client.AddAccount("John", 20);
                Console.WriteLine("Adding Peter , 21 years");
                client.AddAccount("Peter", 21);
                Console.WriteLine("Adding Andrew , 25 years");
                client.AddAccount("Andrew", 25);
                
                DisplayAccounts(client.GetAccounts());            
    
                Console.WriteLine("Removing John");
                client.RemoveAccount(1);
                
                DisplayAccounts(client.GetAccounts());            
    
                client.Close();
    
                Console.WriteLine();
                Console.WriteLine("Press <Enter> to close");
                Console.ReadLine();
            }
    
            private static void DisplayAccounts(string[] accounts)
            {
                Console.WriteLine();
                Console.WriteLine("Current Accounts:");
                foreach (string acc in accounts)
                {
                    Console.WriteLine(acc);
                }
                Console.WriteLine();
            }        
        }
    }

运行服务器,然后运行客户端,并检查结果。

恭喜,您已经创建了一个可用的 WCF 应用程序。

关注点

WCF 使您能够方便地在应用程序之间进行通信。 您可以在更复杂的应用程序中使用它。 使用 MSDN,因为它是一个很大的帮助。

历史

  • 2008 年 7 月 20 日:首次发布
© . All rights reserved.