黑马程序员——初步学习wcf

    今天有人问我会不会wcf,我想wcf是分布式处理吧,但具体不知道杂做了,于是赶紧自己看了看资料,初步自学一下wcf,以免以后再有人问起来咱也能答上来个123。

    我理解的wcf就是分布式处理,也就是说一个程序可以调用另外一个程序的一些功能。也可以说是多台电脑共同处理一些东西。比如,在郑州的一个程序要调用北京一个服务器上的一个方法。

    好了,直接建立项目。新建一个wcf项目,这时会出现两个类IService1.cs,Service1.svc

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService1
{
    // 注意: 如果更改此处的接口名称 "IService1",也必须更新 Web.config 中对 "IService1" 的引用。
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

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


    // 使用下面示例中说明的数据约定将复合类型添加到服务操作。
    [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; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService1
{
    // 注意: 如果更改此处的类名“Service1”,也必须更新 Web.config 和关联的 .svc 文件中对“Service1”的引用。
    public class Service1 : IService1
    {
        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;
        }
    }
}

然后我们在添加一个winform项目作为客户端。客户端要调用服务端的方法。

在新建的窗体上点击右键,选择“添加服务引用”,在点“发现”,就会出现你刚才建立的wcf项目,然后点“前往”,“确定”。

这样我们就能在客户端调用服务端的方法了。

wcftest.Service1Client s = new WindowsFormsApplication1.wcftest.Service1Client();

 label1.Text = s.GetData(34);

其中Service1Client指的类就是Service1。

这样一个简单的wcf例子就搭建好了,这只是我对wcf的初步学习,将来肯定还要深入学习。

原文地址:https://www.cnblogs.com/weiwin/p/2572086.html