WCF基本实现(Server和Client)

来源:互联网 发布:石油化工数据 编辑:程序博客网 时间:2024/06/05 16:59

Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以很多传输协议与WCF服务进行通信。常见的5个协议有:
(1)HTTP:允许与WCF服务通信,可使用HTTP通信技术创建WCF Web服务。
(2)TCP:可以通过TCP协议与WCF服务通信,效率较高。
(3)UDP:采用UDP协议与WCF服务通信。
(4)命名管道:该WCF服务与调用代码位于同一台计算机的不同进程上。
(5)MSMQ:一种排队技术,允许应用同程序发送的小心通过队列路由到目的地。
在常见的应用中HTTP和TCP应用较为普遍,WCF大大降低了编程难度,但是WCF配置一直是一大难点。构建一个WCF程序通常分为三个部分:服务类(Server)、宿主(Host)、客户程序(Client)。为了让Server和Client可以顺利通信,双方应该根据契约定义相关的操作和数据。例如客户端要向服务端请求获取相关的学生信息,此时我们可以先定义学生的数据结构,其具体如下:

 [DataContract]   public class StudentInfo    {        [DataMember]        public string Name { get; set; }        [DataMember]        public int StudentID { get; set; }        [DataMember]        public string University { get; set; }    }
此时我们应该定义相关操作契约接口,其具体如下:
   [ServiceContract]    public interface IStudentContract    {        [OperationContract]   //操作约定        StudentInfo GetStudentInfo();    }
此时已经成功定义好了数据结构和相关的操作协定,Server端应该实现IStudentContract接口,然后Client可以向Server发送请求获取相关学生信息,其Server端的详细实现如下:
  public class StudentDataService : IStudentContract    {        public StudentInfo GetStudentInfo()        {            StudentInfo info = new StudentInfo()             { Name = "Mike", StudentID = 100, University = "HUST" };            return info;        }    }

至此服务Server端已经实现了其契约相关接口,接下来需要将Server寄宿到相关程序(window服务、exe可执行程序或者IIS等)。为了简化处理,采用寄宿到控制台里,相关代码如下:

 static void Main(string[] args)        {            ServiceHost host = new ServiceHost(typeof(StudentDataService ));            host.Open();            Console.WriteLine("正在监听:" );            Console.ReadKey();        }

此时应该在此控制台的配置文件App.config里面添加如下配置,详细如下:

 <system.serviceModel>    <bindings>      <netTcpBinding>        <binding name="NewBinding0" openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">          <security mode="None"/>        </binding>      </netTcpBinding>    </bindings>    <behaviors>      <serviceBehaviors>        <behavior name="myBehavior">          <serviceMetadata httpGetEnabled="False"/>          <serviceDebug includeExceptionDetailInFaults="true"/>        </behavior>      </serviceBehaviors>    </behaviors>    <services>      <service name="StudentDataService" //注意添加上命名空间 behaviorConfiguration="myBehavior">        <endpoint address="net.tcp://localhost:8126/StudentDataService" binding="netTcpBinding" bindingConfiguration="NewBinding0" contract="IStudentContract"/>  //注意添加上命名控件      </service>    </services>  </system.serviceModel>

为了测试相关功能是否正常,Client测试的相关代码如下:

static void Main(string[] args)        {        var factory = new ChannelFactory<IStudentContract>("TestStudentClient");  //此名名保持和配置文件中一致            IStudentContract_channel = factory.CreateChannel();            while (true)            {                StudentInfo info = _channel.GetStudentInfo();                Console.WriteLine("姓名:" + info.Name);                Console.WriteLine("学号:" + info.StudentID);                Console.WriteLine("学校:" + info.University);                Thread.Sleep(10000);            }            Console.ReadKey();        }

相关配置如下:

<system.serviceModel>    <bindings>      <netTcpBinding>        <binding name="NewBinding0" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">          <security mode="None"/>        </binding>      </netTcpBinding>    </bindings>    <client>      <endpoint address="net.tcp://localhost:8126/TextDataService" binding="netTcpBinding" bindingConfiguration="NewBinding0" contract="IStudentContract" name="TestStudentClient" kind="" endpointConfiguration=""/>    </client>  </system.serviceModel>

至此服务Server和Client的代码基本完成。本文主要是采用netTcp方式进行WCF通信,经过测试Client可以从Server获取到相关数据。