WCF学习之“单向服务”

来源:互联网 发布:淘宝店过户有没有风险 编辑:程序博客网 时间:2024/06/05 20:39

1、打开Visual Studio 2008

2、新建项目 à 选择项目类型:Visual C#下的WCF à WCF服务库(WCF Service Library à 确认项目名称以后,点击“确定”。(该Sample中使用WcfServiceLibrary1作为项目的名称)

3、打开IService1.cs文件,并修改其中的内容,完整代码如下所示。

using System.Runtime.Serialization;

using System.ServiceModel;

namespace WcfServiceLibrary1

{

    [ServiceContract]

    public interface IService1

    {

        [OperationContract]

        string GetData(int value);

        [OperationContract]

        CompositeType GetDataUsingDataContract(CompositeType composite);

        [OperationContract(IsOneWay=true)]

        void TestMethod(string paraInput); // 单向服务不允许有返回值

    }

    [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; }

        }

    }

}

4、打开Service1.cs,并修改其中的内容,完整代码如下所示。

namespace WcfServiceLibrary1

{

   public class Service1 : IService1

    {

        public string GetData(int value)

        {

            System.Threading.Thread.Sleep(5000); // 单向服务的对比测试方法

            return string.Format("You entered: {0}", value);

        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)

        {

            if (composite.BoolValue)

            {

                composite.StringValue += "Suffix";

            }

            return composite;

        }

        public void TestMethod(string paraInput)

        {

            System.Threading.Thread.Sleep(5000); // 单向服务的测试方法

        }

    }

}

5、生成WCF项目。

6、添加一个Windows窗口程序。

7、为Windows窗口程序添加一个服务引用 à 在“添加服务引用”窗口中点击“发现”就显示出本机模拟的一个WCF服务程序 à 点击“确定”,将其添加到程序中。

8、在窗口中添加一个按钮à在按钮事件中添加如下代码。

            ServiceReference1.Service1Client sc = new WindowsFormsApplication1.ServiceReference1.Service1Client();

            MessageBox.Show(sc.GetData(3));

9、在窗口中再添加一个按钮,做对比试验à在按钮事件中添加如下代码:

            ServiceReference1.Service1Client sct = new WindowsFormsApplication1.ServiceReference1.Service1Client();

            sct.TestMethod("这是一个单项服务传递的测试");

10、实例代码编写完成,运行程序查看效果。

点击按钮1:需要等待5秒钟后才接受到从服务器端传回的值。

点击按钮2:无需等待服务器端应答。