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,這是自己寫的第一個簡單的程序,比較簡單。