WCF实例

来源:互联网 发布:淘宝怎么设置全场包邮 编辑:程序博客网 时间:2024/05/29 17:50

WCF实例

以订票为例简单应用wcf
新建一个wcf服务应用程序[文件\新建\项目\WCF服务应用程序],命名为WcfDemo


在IService1.cs定义服务契约

namespace WcfDemo
{
    // 注意: 如果更改此处的接口名称 "IService1",也必须更新 Web.config 中对 "IService1" 的引用。
     [ServiceContract]  // 服务合同 即提供服务的接口或类
    public interface IService1
     {

         [OperationContract]
        /* 增加车票的方法*/
        void AddTicket(int count);

         [OperationContract]
        /*购买车票的方法*/
        int BuyTickets(int Num);

         [OperationContract]  //服务契约   即提供服务的实现方法
        /*查询车票的方法*/
      
        int GetRemainingNum();

        // 任务: 在此处添加服务操作
     }


    // 使用下面示例中说明的数据约定将复合类型添加到服务操作。
     [DataContract]   //数据契约  
    public class Ticket
     {
        bool boolCount = true;//判断是否还有车票
        int howmany = 10;//还有多少车票
       
         [DataMember]
        /*判断是否还有票*/
        public bool BoolCalue
         {
            get { return boolCount; }
            set {
                if (HowMany > 0)
                 {
                     boolCount = false;
                 }
                else
                 {
                     boolCount = true;
                 }
             }
         }

         [DataMember]
        /*返回票数*/
        public int HowMany
         {
            get { return howmany; }
            set { howmany = value;}
         }
     
     }
}在Service1.svc中实现契约服务
namespace WcfDemo
{
    // 注意: 如果更改此处的类名“Service1”,也必须更新 Web.config 和关联的 .svc 文件中对“Service1”的引用。
    public class Service1 : IService1
     {  
         Ticket T=new Ticket();
        /*实现添加票数的方法*/
        public void   AddTicket(int count)
         {
             T.HowMany=T.HowMany+count;
         }
        /*实现返回票数的方法*/
        public int GetRemainingNum()
         {
           
            return T.HowMany;
         }
        /*实现购买车票的方法*/
        public int BuyTickets(int Num)
         {
            if (T.BoolCalue)
             {
                 T.HowMany = T.HowMany - Num;
                return 1;
             }
            else
             {
                return 0;
             }
           
         }
     }
}添加宿主程序用于监测服务
添加WinForm项目加入解决方案
Form1界面内容:
启动服务按钮: 用于启动wcf服务
停止服务按钮: 用于停止wcf服务
Label:   用于显示服务相关信息
后台代码为:
应用命名空间 using System.ServiceModel;
添加引用 wcf服务生成的dll文件

public partial class Form1 : Form
     {
        public Form1()
         {
             InitializeComponent();
         }
         ServiceHost host = null;//定义 ServiceHost
        private void button1_Click(object sender, EventArgs e)
         {
             host = new ServiceHost(typeof(WcfDemo.Service1));//WcfDemo.Service1 为引用的dll中的服务
             host.Open();//启动服务
            this.label1.Text = "服务已启动";

/*

//将注释这段注释代码替换当前方法后不需要增加配置文件

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

*/

         }

        private void button2_Click(object sender, EventArgs e)
         {
            if (host.State != CommunicationState.Closed)//判断服务是否关闭
             {
                 host.Close();//关闭服务
             }
            this.label1.Text = "服务已关闭";
         }
     }

接下来配置app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.serviceModel>
      <services><!--添加服务-->
        <service name="WcfDemo.Service1" behaviorConfiguration="CalculatorServiceBehavior">
          <!--name 必须与代码中的host实例初始化的服务一样  
            behaviorConfiguration 行为配置 -->
          <host>
            <baseAddresses>
              <!--添加调用服务地址-->
              <add baseAddress="http://localhost:8000/"/>
            </baseAddresses>
            
          </host>
          <!--添加契约接口   contract="WcfDemo.IService1" WcfDemo.IService1为契约接口   binding="wsHttpBinding" wsHttpBinding为通过Http调用-->
          <endpoint address=""    binding="wsHttpBinding" contract="WcfDemo.IService1"></endpoint>
        </service>
        
      </services>
     <!--定义CalculatorServiceBehavior的行为-->
     <behaviors>
        <serviceBehaviors>
          <behavior name="CalculatorServiceBehavior">
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
            
          </behavior>
          
        </serviceBehaviors>
        
      </behaviors>
    </system.serviceModel>
</configuration>

运行程序.并点启动服务

在服务启动后可通过appConfig中baseAddress节点中的baseAddress地址查看Wcf服务(如:在IE中输入:http://localhost:8000)

到这服务以及服务主机都已经创建好了下面该创建测试客户机了!
新建个WinForm程序做为我们的测试客户机
界面两个按钮一个label

购买车票:调用wcf服务的BuyTickets()方法
查询车票:调用wcf服务的GetRemainingNum()方法
label用于显示运行信息
为项目添加服务引用 地址输入服务主机appconfig中baseAddress地址点击前往(添加服务引用时一点是在服务启动状态下的)

后台代码为:

public partial class Form2 : Form
     {
        public Form2()
         {
             InitializeComponent();
         }
         ServiceReference1.Service1Client TClient = new WinFormsClient.ServiceReference1.Service1Client();
        //声明客户端调用
        private void button1_Click(object sender, EventArgs e)
         {
            int i = TClient.BuyTickets(2); //调用WCF中的方法
            if (i == 1)
             {
                this.label1.Text = "购买成功";
             }
            this.label1.Text += "剩余车票还有" + TClient.GetRemainingNum().ToString();
         }

        private void button2_Click(object sender, EventArgs e)
         {
            this.label1.Text = "";
            this.label1.Text = TClient.GetRemainingNum().ToString();//调用WCF中的方法
         }

      
     }

点击购买车票时调用wcf的BuyTicket()方法并返回剩余车票的信息
点击查看车票时调用wcf的GetRemainingNum()得到剩余车票信息

运行客户端

0 0
原创粉丝点击