WCF初见之HelloWorld

1.直接创建一个WCF服务应用程序,项目名称为“HelloWorld”,如下图:

2.然后再IService1.cs中定义 WCF服务协定,具体代码如下:

using System;
using System.ServiceModel;

namespace HelloWorld
{//定义协定,协定指定服务支持的操作
    [ServiceContract]
    //定义一个名为IService1的接口
    public interface IService1
    {
        //在接口中为IService1协定公开的每个操作声明一个方法
        [OperationContract]
         string Hello();
    }
}

 

3.再在Service1.svc.cs中实现WCF服务协定,具体代码如下:

using System;
using System.ServiceModel;

namespace HelloWorld
{
    //在Service1类中实现在IService1接口中定义的每个方法
    public class Service1 : IService1
    {
        public string Hello()
        {
            return " Hello World!";
        }
    }
}

4.启动服务,得到服务地址

 5.新建一个控制台程序,命名为HelloShow,然后添加服务引用,如下图所示:

 

6.然后就是在Program.cs中编写客户端代码了,具体代码如下:

using System;
//添加一个使用命名空间System.ServiceModel的声明
using System.ServiceModel;

namespace HelloShow
{
    class Program
    {
        static void Main(string[] args)
        {
            host.Service1Client h = new host.Service1Client();
            //输出从服务端的到的数据
            Console.WriteLine(h.Hello());
            Console.ReadLine();
        }
    }
}

7.现在就可以运行下了,效果图如下:

 

PS:最近开始接触WCF,这是自己写的第一个简单的程序,比较简单。

 

posted @ 2012-06-08 20:38  叶超Luka  阅读(4642)  评论(1编辑  收藏  举报