WCF初识

最近公司把我分配到了数据组,个人也被分配到了数据住主管同步数据,主要负责用WCf开发大同步数据,开始学习!!!

统计应该有四点可以借鉴:1、统一性2、互操作性3、安全与可信赖4、兼容性

借引:简单的订票服务

示例代码Iservice1.cs即为服务契约接口文件,服务要实现的操作可以通过接口来定义

using System;

using System.Collections.Generic;

using System.Runtime.Serialization;

using System.ServiceModel;

namespace WcfService1

{    

//注意:如果更改此处的接口名称"IService1",也必须更新Web.config中对"IService1"的引用。    

[ServiceContract]   

  public interface IService1  

   {    

     [OperationContract]     

    int GetRemainingNum();

        [OperationContract]  

       List<Tickets> BuyTickets(int Num);   

  }

    // 服务契约数据定义   

  [DataContract]    

public class Tickets   

  {       

  //假设还有1张,编号是"23"       

  int remainingNum = 1;   

      string ticketID = "23";

        /// <summary>     

    /// 剩余数量        

/// </summary>     

    [DataMember]        

public int RemainingNum       

  {            

get { return remainingNum; }      

       set { remainingNum = value; }     

    }        

/// <summary>        

/// 车票编号      

   /// </summary>        

[DataMember]      

   public string TicketID      

   {           
  get { return ticketID; }     

        set { ticketID = value; }   

      }

    }

}

服务实现起始就是对契约(接口)的实现,继承接口并实现方法

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace WcfService1
{
    // 注意: 如果更改此处的类名“Service1”,
    //也必须更新Web.config和关联的.svc文件中对“Service1”的引用
    public class Service1 : IService1
    {
        //查询剩余数量
        public int GetRemainingNum()
        {
            Tickets tic = new Tickets();
            return tic.RemainingNum;
        }
        //购买票
        public List<Tickets> BuyTickets(int Num)
        {
            //自己的业务逻辑代码实现,这里只是举例
            Tickets tick = new Tickets();
            if (Num > 0)
            {
                tick.RemainingNum--;
            }
            List<Tickets> ticklist = new List<Tickets>();
            ticklist.Add(tick);
            return ticklist;
        }
    }
}

宿主进程:要想使wcf服务运行,需要宿主进程,即wcf服务不可能凭空存在。每个wcf服务必须托管hosting在windows进程中,该进程就称为宿主进程。宿主可以有iis提供,也可以有windows form 程序或windows 服务提供,或者有 console 控制台程序提供。

配置文件:对刚才实现的wcf服务的库引用:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>  

   <system.serviceModel>

        <services>   

          <service     name="WcfService1.Service1"     behaviorConfiguration="CalculatorServiceBehavior">    

             <host>                    

<baseAddresses>                

         <add baseAddress="http://localhost:8000/"/>   

                  </baseAddresses>      

           </host>                            

   <endpoint address=""         binding="wsHttpBinding"         contract="WcfService1.IService1" />      

       </service>

</services>

        <!--为了调试,设置 includeExceptionDetailInFaults 属性等于true.-->    

     <behaviors>          

   <serviceBehaviors>  

               <behavior name="CalculatorServiceBehavior">      

               <serviceMetadata httpGetEnabled="True"/>          

           <serviceDebug includeExceptionDetailInFaults="False" />     

            </behavior>       

      </serviceBehaviors>   

      </behaviors>    

</system.serviceModel>

</configuration>

启动服务:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Windows.Forms;

using System.ServiceModel;

namespace WindowsFormsWcfApp

{

    public partial class Form1 : Form  

   {

        public Form1()      

   {

            InitializeComponent();  

       }

        //声明宿主       

  ServiceHost host =null;

                private void btnStart_Click(object sender, EventArgs e)

        {  

           host = new ServiceHost(typeof(WcfService1.Service1));

            host.Open();//启动服务的监听器信道,监听请求     

                                //host.AddServiceEndpoint(typeof(IMyProcess), new BasicHttpBinding(), "manualWCF");             //ServiceMetadataBehavior smb = new ServiceMetadataBehavior();      

       //smb.HttpGetEnabled = true;          

   //host.Description.Behaviors.Add(smb);   

          label1.Text = "订票服务已启动";   

      }

        private void btnStop_Click(object sender, EventArgs e)      

   {           

  if (host.State != CommunicationState.Closed)   

          {           

      host.Close();//停止信道     

        }         

    label1.Text = "订票服务已停止";        

    }

  }

}

调用服务:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace WCFClientApp

{

    public partial class Form1 : Form   

  {

        public Form1()     

    {             InitializeComponent();         }

        private void button1_Click(object sender, EventArgs e)   

      {

TicketServiceRef.Service1Client wcfClient = new TicketServiceRef.Service1Client();

int n=wcfClient.GetRemainingNum();//查询剩余数量

TicketServiceRef.Tickets[] tickets=wcfClient.BuyTickets(1);//购买一张票         

            } 

    }

}

原文地址:https://www.cnblogs.com/hjhd/p/2941980.html