WCF学习总结

来源:互联网 发布:淘宝门 编辑:程序博客网 时间:2024/05/16 12:27

 

(部分内容来自网络,在网络找的资料 学习的,在这里整理下,本文适合初学者)

源码下载:http://download.csdn.net/detail/li0531/5172849

工具:vs2008

 

【服务端】

1. 新建项目

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

项目整体演示:

 

 

 

 

 

1   是接口类      (系统默认)

2.  实现接口类 (系统默认)

3.  配置文件      (系统默认)

 

直接打开 IService1 添加代码如下

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.Text;namespace WCFserver{    //源码下载:http://download.csdn.net/detail/li0531/5172849    // 注意: 如果更改此处的接口名称“IService1”,也必须更新 App.config 中对“IService1”的引用。    //服务合同 即提供服务的接口或类    [ServiceContract]    public interface IService1    {        //[OperationContract]        //string GetData(int value);        //[OperationContract]        //CompositeType GetDataUsingDataContract(CompositeType composite);        // 任务: 在此处添加服务操作        [OperationContract]        /* 增加车票的方法*/        void AddTicket(int count);        [OperationContract]        /*购买车票的方法*/        int BuyTickets(int Num);        [OperationContract]  //服务契约   即提供服务的实现方法        /*查询车票的方法*/        int GetRemainingNum();    }    // 使用下面示例中说明的数据协定将复合类型添加到服务操作    [DataContract]    public class CompositeType    {        //bool boolValue = true;        //string stringValue = "Hello ";        //[DataMember]        //public bool BoolValue        //{        //    get { return boolValue; }        //    set { boolValue = value; }        //}        //[DataMember]        //public string StringValue        //{        //    get { return stringValue; }        //    set { stringValue = value; }        //}        //添加        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:

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.Text;namespace WCFserver{    // 注意: 如果更改此处的类名“IService1”,也必须更新 App.config 中对“IService1”的引用。    public class Service1 : IService1    {        //初始化 类        CompositeType T = new CompositeType();        //public string GetData(int value)        //{        //    return string.Format("You entered: {0}", value);        //}        //public CompositeType GetDataUsingDataContract(CompositeType composite)        //{        //    if (composite.BoolValue)        //    {        //        composite.StringValue += "Suffix";        //    }        //    return composite;        //}        #region IService1 成员        /*实现添加票数的方法*/        public void AddTicket(int count)        {            T.HowMany = T.HowMany + count;        }        /*实现购买车票的方法*/        public int BuyTickets(int Num)        {            if (T.BoolCalue)            {                T.HowMany = T.HowMany - Num;                return 1;            }            else            {                return 0;            }        }        /*实现返回票数的方法*/        public int GetRemainingNum()        {             return T.HowMany;        }        #endregion    }}


App.config 文件里面不用动 因为 我们的类  直接 在默认类添加的代码 默认就行

 

在解决方案上 添加项目 实现打开服务功能

WCFtest

界面如下:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

窗体代码:

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;using System.ServiceModel;namespace WCFtest{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        //定义 ServiceHost        ServiceHost host = null;        private void btnopen_Click(object sender, EventArgs e)        {            int flag = -1;            try            {                //错误信息                //0 打开 异常                //1 关闭异常                //开启服务                if (btnopen.Text == "开启服务")                {                    flag = 0;                    btnopen.Text = "关闭服务";                    //WCFserver.Service1 为引用的dll中的服务                    host = new ServiceHost(typeof(WCFserver.Service1));                    //启动服务                    host.Open();                    this.labmsg.Text = "服务已启动";                }                else                {                    flag = 1;                    btnopen.Text = "开启服务";                    if (host.State != CommunicationState.Closed)//判断服务是否关闭                    {                        host.Close();//关闭服务                    }                    this.labmsg.Text = "服务已关闭";                }            }            catch (Exception ex)            {                switch (flag)                {                    case 0:                        MessageBox.Show("开启服务异常:" + ex.ToString());                        break;                    case 1:                        MessageBox.Show("关闭服务异常:" + ex.ToString());                        break;                    default:                        break;                }            }        }    }}


 添加 App.config 文件

<?xml version="1.0" encoding="utf-8" ?><configuration>  <system.serviceModel>    <services>      <!--添加服务-->      <service name="WCFserver.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="WCFserver.IService1"></endpoint>      </service>    </services>    <!--定义CalculatorServiceBehavior的行为-->    <behaviors>      <serviceBehaviors>        <behavior name="CalculatorServiceBehavior">          <serviceMetadata httpGetEnabled="true"/>          <serviceDebug includeExceptionDetailInFaults="false"/>        </behavior>      </serviceBehaviors>    </behaviors>  </system.serviceModel></configuration>


【客户端】

添加测试项目 WCFtext

添加web引用  如下图

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

添加界面 如图(当然了 你可以整理漂亮些 在这里只是做了个了例子)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

代码实习如下:

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 WCFtext{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        //初始化方法        ServiceReference1.Service1Client TClient = new WCFtext.ServiceReference1.Service1Client();        //购买车票        private void btnshapping_Click(object sender, EventArgs e)        {            int num =Convert.ToInt32(txtnums.Value.ToString());            if (TClient.GetRemainingNum()<=0)            {                this.labmsg.Text = "无票";                return;            }            if (TClient.GetRemainingNum() < num)            {                this.labmsg.Text = "车票不足,剩余" + TClient.GetRemainingNum().ToString()+"张";                return;            }            int i = TClient.BuyTickets(num); //调用WCF中的方法            if (i == 1)            {                this.labmsg.Text = "购买成功" + num.ToString() + "张成功!";            }            this.labmsg.Text += "剩余车票还有" + TClient.GetRemainingNum().ToString()+"张";        }        //查询票价        private void btngetpj_Click(object sender, EventArgs e)        {            this.labmsg.Text = "";            this.labmsg.Text = TClient.GetRemainingNum().ToString();        }        //添加车票        private void btnadd_Click(object sender, EventArgs e)        {            TClient.AddTicket(Convert.ToInt32(txtnum.Value.ToString()));            this.labmsg.Text = "添加" + txtnum.Value.ToString() + "张票成功" + "剩余车票还有" + TClient.GetRemainingNum().ToString();        }        private void Form1_Load(object sender, EventArgs e)        {            labsf.Text = "始发站:济南 D110( 9:30)";            labzd.Text = "终点站:巨野 D110(12:51)";            txtnums.Value = 1;            txtnum.Value = 1;        }    }}


效果图:

 

代码到此结束----

祝你好运 !

 

 

 

原创粉丝点击