WCF 简单示例程序(源码下载)

WCF 简单示例程序(源码下载)

 


本示例程序演示如何编写一个简单的WCF 示例程序。


 

示例WCF 项目源码下载



如何使用WCF 示例代码:
Server 端:Console 程序,WCF Service 承载在Console 程序中。

    [ServiceContract(Namespace = "http://microsoft.servicemodel.samples/")]
    public interface IBankService
    {
        [OperationContract]
        int AddAccount(string clientName, int clientAge);
        [OperationContract]
        bool RemoveAccount(int accountNumber);
        [OperationContract]
        List<String> GetAccounts();
    }

    class BankService: IBankService
    {
        private List<Account> _accounts = new List<Account>();
        private int _idGenerator = 0;

        public int AddAccount(string clientName, int clientAge)
        {
            Console.WriteLine(OperationContext.Current.SessionId);

            _idGenerator++;
            Account acc = new Account(_idGenerator, clientName, clientAge);
            _accounts.Add(acc);
            Console.WriteLine("ADD - " + acc.ToString());
            return _idGenerator;
        }
......

Client 端: 也是一个Console 程序,负责调用/测试 WCF Services。
            using (ChannelFactory<IBankService> bankFactory =
               new ChannelFactory<IBankService>("MyClient"))
            {
                IBankService bankProxy = bankFactory.CreateChannel();

                Console.WriteLine("Adding John , 20 years");
                bankProxy.AddAccount("John", 20);
                Console.WriteLine("Adding Peter , 21 years");
                bankProxy.AddAccount("Peter", 21);
                Console.WriteLine("Adding Andrew , 25 years");
                bankProxy.AddAccount("Andrew", 25);

                DisplayAccounts(bankProxy.GetAccounts());

                Console.WriteLine("Removing John");
                bankProxy.RemoveAccount(1);

                DisplayAccounts(bankProxy.GetAccounts());


                Console.WriteLine();
                Console.WriteLine("Press <Enter> to close");
                Console.ReadLine();
            }

运行WCF 示例项目:

启动WCF Server 端 Console 程序,运行界面如下:



下面是通过C# Application 调用上述WCF Service 的运行情况:




恭喜!你现在已经完成了一个WCF Service 程序!

 

 

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页