WCF后续之旅(17):通过tcpTracer进行消息的路由
对于希望对WCF的消息交换有一个深层次了解的读者来说,tcpTracer绝对是一个不可多得好工具。我们将tcpTracer置于服务和服务代理之间,tcpTracer会帮助我们接获、显示和转发流经他的消息。
从本质上讲,tcpTracer是一个路由器。当启动的时候,我们需要设置两个端口:原端口(source port)和目的端口(destination port),然后tcpTracer就会在原端口进行网络监听。一旦请求抵达,他会截获整个请求的消息,并将整个消息显示到消息面板上。随后,tcpTracer会将该消息原封不动地转发给目的端口。在另一方面,从目的端口发送给原端口的消息,也同样被tcpTracer截获、显示和转发。
接下来我们我们通过下面的步骤演示如何通过tcpTracer在WCF中进行消息的路由。
步骤一、创建一个简单的WCF应用
为了演示tcpTracer在WCF中的应用,我们需要先创建一个简单的WCF服务的应用,为此我们创建一个简单计算服务的例子。
整个应用采用如下图所示的四层结构:Contracts、Services、Hosting和Clients。
- Contracts:class library项目,定义所有的契约,包括服务契约、数据契约、消息契约以及错误契约,刚项目同时被其他三个项目引用
- Services:class library项目,实现了在Contracts中定义的服务契约
- Hosting:控制台项目,同时引用Contracts和Services,实现对定义在Services项目的服务的寄宿
- Clients:控制台项目,引用Contracts,模拟服务的调用者
服务契约:Artech.TcpTraceDemo.Contracts.ICalculate
1: //---------------------------------------------------------------
2: // EndpointAddress & WCF Addressing (c) by 2008 Jiang Jin Nan
3: //---------------------------------------------------------------
4: using System.ServiceModel;
5: namespace Artech.TcpTraceDemo.Contracts
6: {
7: [ServiceContract]
8: public inte易做图ce ICalculate
9: {
10: [OperationContract]
11: double Add(double x, double y);
12: }
13: }
服务实现:Artech.TcpTraceDemo. Services. CalculateService
1: //---------------------------------------------------------------
2: // EndpointAddress & WCF Addressing (c) by 2008 Jiang Jin Nan
3: //---------------------------------------------------------------
4: using Artech.TcpTraceDemo.Contracts;
5:
6: namespace Artech.TcpTraceDemo.Services
7: {
8: public class CalculateService:ICalculate
9: {
10: #region ICalculate Members
11:
12: public double Add(double x, double y)
13: {
14: return x + y;
15: }
16:
17: #endregion
18: }
19: }
服务寄宿(代码):Artech.TcpTraceDemo.Hosting. Program
1: //---------------------------------------------------------------
2: // EndpointAddress & WCF Addressing (c) by 2008 Jiang Jin Nan
3: //---------------------------------------------------------------
4: using System;
5: using System.ServiceModel;
6: using Artech.TcpTraceDemo.Services;
7:
8: namespace Artech.TcpTraceDemo.Hosting
9: {
10: class Program
11: {
12: static void Main(string[] args)
13: {
14: using (ServiceHost serviceHost = new ServiceHost(typeof(CalculateService)))
15: {
16: serviceHost.Opened += delegate
17: {
18: Console.WriteLine("The Calculate Service has been started up!");
19: };
20: serviceHost.Open();
21:
22: Console.Read();
23: }
24: }
25: }
26: }
27:
服务寄宿(配置):App.config
1: <?xml version="1.0" encoding="utf-8" ?>
2: <configuration>
3: <system.serviceModel>
4: <bindings>
5: <customBinding>
6: <binding name="SimpleBinding">
7: <textMessageEncoding />
8: <httpTransport />
9: </binding>
10: </customBinding>
11: </bindings>
12: <services>
13: <service name="Artech.TcpTraceDemo.Services.CalculateService">
14: <endpoint address="
补充:综合编程 , 其他综合 ,