(WCF) 二、一个简单的WCF例子

系列索引,请查看此

 

这里简单写一个创建WCF用例的例子:

 

一、创建服务端

创建服务端(Service)

1. 创建服务端接口

// Step 6: Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface ICalculator
    {
        // Step7: 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);
    }

 

2. 实现服务端接口

    // Step 1: Create service class that implements the service contract.
    public class CalculatorService : ICalculator
    {
        // Step 2: Implement functionality for the service operations.
        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}. do good ! very good !!", result);
            return result;
        }
    }

 

二、部署服务端

  本项目选择直接用后台控制程序 承载 WCF服务,所以需要写点代码公布外面的访问路径;(也可以使用其他方式承载,如IIS)

1. 在服务端的运行入口写入

  

class Program
    {
        private static Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

        static void Main(string[] args)
        {
            // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
            Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

            // Step 2 of the hosting procedure: Create ServiceHost
            ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

            try
            {
                // Step 3 of the hosting procedure: Add a service endpoint.
                selfHost.AddServiceEndpoint(
                    typeof(ICalculator),
                    new WSHttpBinding(),
                    "CalculatorService");


                // Step 4 of the hosting procedure: Enable metadata exchange.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                selfHost.Description.Behaviors.Add(smb);

                // Step 5 of the hosting procedure: 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();
            }


        }
    }

 

2.  生成服务端项目,运行服务端

三、成客户端代理

1. 如第一步,创建客户端项目(Client)

2. 生成客户端代理。

  有两种方式,一般:

  a. 通过命令生成客户端代理

  b.直接引用服务端项目。

  一般的场景,直接(b)种方式,很简单:

  

 

 

 但是,我们不是IIS承载的服务,所以用(b)种方式,不能发现。此外,(a)种方式虽然麻烦,却是最有威力的,试想,假如是其他公司为你开的服务,并不让你直接引用,你怎么办?生成客户端代理吧!

 

  在“开始”菜单上,单击“所有程序”,然后单击“Visual Studio 2010”。单击“Visual Studio 工具”,然后单击“Visual Studio 2010 命令提示”

   svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service

  3. 将生成的代理,移入客户项目

 

同时,将生成的配置文件,相关的配置也移入客户端app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_ICalculator" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Message">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite="Default" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:8000/ServiceModelSamples/Service/CalculatorService"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator"
                contract="ICalculator" name="WSHttpBinding_ICalculator">
                <identity>
                    <userPrincipalName value="dengfuyong-PC\dengfuyong" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

 

四、客户端调用

1. 编写调用方式:

  CalculatorClient client = new CalculatorClient();

            // 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();


2. 运行

 

这里,我们发现:客户端有服务端可以双向通信。简单可以看出:WCF 至少具有WebService和Remoting的功能。

 

总结

   做一个WCF应用,实际上分为:创建服务端接口、并实现接口;客户端引用(可以通过生成代理的方式)、客户端调用。微软的官方文档如下说:

   

    1. 定义服务协定。服务协定指定服务的签名、服务交换的数据和其他协定要求的数据。
    2. 实现协定。若要实现服务协定,请创建实现协定的类并指定运行时应具有的自定义行为。
    3. 通过指定终结点和其他行为信息来配置服务。
    4. 承载服务。
    5. 生成客户端应用程序。

 

 

今天早上到此结束吧。

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 C# WCF 服务的例子: 首先,在 Visual Studio 中创建一个新的 WCF 服务应用程序项目。然后,在服务契约中定义一个简单的操作: ```C# [ServiceContract] public interface IMyService { [OperationContract] string GetMessage(string name); } ``` 这个操作接受一个字符串类型的参数,返回一个字符串类型的消息。 接下来,在服务实现中实现这个操作: ```C# public class MyService : IMyService { public string GetMessage(string name) { return "Hello, " + name + "!"; } } ``` 这个实现接受一个字符串类型的参数,返回一个拼接了该参数的消息。 然后,在配置文件中定义一个终结点: ```XML <system.serviceModel> <services> <service name="MyService"> <endpoint address="http://localhost:8080/MyService" binding="basicHttpBinding" contract="IMyService"/> </service> </services> </system.serviceModel> ``` 这个终结点定义了服务的地址、绑定和契约等信息。 最后,在 host 中启动服务: ```C# ServiceHost host = new ServiceHost(typeof(MyService)); host.Open(); ``` 这个 host 启动了 MyService 类型的服务。 现在,WCF 服务已经启动并且可以接收客户端的请求。在客户端中,你可以使用类似下面的代码来调用服务: ```C# ChannelFactory<IMyService> factory = new ChannelFactory<IMyService>( new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/MyService")); IMyService proxy = factory.CreateChannel(); string message = proxy.GetMessage("World"); Console.WriteLine(message); ``` 这个客户端创建了一个 IMyService 类型的代理对象,并调用了它的 GetMessage 方法,将 "World" 作为参数传递,并将返回的消息打印到控制台上。 这就是一个简单的 C# WCF 服务的例子,它展示了如何定义服务契约、实现服务操作、配置服务终结点和启动服务 host。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值