在WCF中一些基于HTTP之上的绑定可以用TcpTrace跟踪消息。借助此工具可以使我们有机会了解一些功能的工作方式,如可靠性会话在网络断开的情况下是如何向服务端发送消息。
TcpTrace的界面非常简洁,简洁的有点让人不知所措。
Listen on Port:TcpTrace要监听的本机端口
Destination Server:对TcpTrace监听的端口的任何访问都将转发到目标服务器
Destination Port:对TcpTrace监听的端口的任何访问都将转发到目标服务器的这个端口
如在浏览地址栏输入:http://127.0.0.1:8080或者http://localhost:8080,将会自动转发到对http://www.google.com:80的访问,
结果如图:
简单的了解了下TcpTrace如何工作的,下面写个实例来演示用它如何跟踪WCF消息。
实体类:
using System.ServiceModel;
using System.Runtime.Serialization;
namespace FruitModel
{
[DataContract(Namespace = " http://www.cnblogs.com/qiuwuyu " )]
public class Fruit
{
private string m_Name;
private string m_Price;
[DataMember]
public string Name
{
get { return m_Name; }
set { m_Name = value;}
}
[DataMember]
public string Price
{
get { return m_Price; }
set { m_Price = value;}
}
}
}
服务契约:
using System.ServiceModel;
using FruitModel;
namespace IFruit
{
[ServiceContract(Namespace = " http://www.cnblogs.com/qiuwuyu " )]
public interface IFruitService
{
[OperationContract]
Fruit GetFruit();
}
}
服务实现:
using System;
using FruitModel;
using IFruit;
namespace FruitSvc
{
public class FruitService:IFruitService
{
public Fruit GetFruit()
{
Fruit f = new Fruit();
f.Name = " banana " ;
f.Price = " 6.00 " ;
return f;
}
}
}
寄存服务:
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using IFruit;
using FruitSvc;
namespace FruitHost
{
class Program
{
static void Main( string [] args)
{
using (ServiceHost host = new ServiceHost( typeof (FruitService),
new Uri( " http://localhost:8000 " )))
{
WSHttpBinding binding = new WSHttpBinding();
binding.ReliableSession.Enabled = true ;
binding.Security.Mode = SecurityMode.None;
// 改变地址端口为8080,这样可以支持服务消息发送到8080端口,8000设置为监听端口
host.AddServiceEndpoint( typeof (IFruitService), binding, new Uri( " http://localhost:8080/FruitService " ),
new Uri( " http://localhost:8000/FruitService " ));
host.Open();
Console.WriteLine( " Fruit Service Is Running... " );
Console.ReadLine();
}
}
}
}
客户端调用:
using System;
using System.ServiceModel;
using IFruit;
using FruitModel;
namespace FruitClient
{
class Program
{
static void Main( string [] args)
{
EndpointAddress epAddr = new EndpointAddress( " http://localhost:8080/FruitService " );
WSHttpBinding wsbinding = new WSHttpBinding();
wsbinding.ReliableSession.Enabled = true ;
wsbinding.Security.Mode = SecurityMode.None;
using (ChannelFactory < IFruitService > factory = new ChannelFactory < IFruitService > (wsbinding, epAddr))
{
IFruitService proxy = factory.CreateChannel();
Fruit f = proxy.GetFruit();
if (f != null )
{
Console.WriteLine( " Name: " + f.Name + " Price: " + f.Price);
}
}
Console.WriteLine( " Fruit Client Is Running... " );
Console.ReadLine();
}
}
}
可以看到现在客户端访问的服务端口为8080,而服务监听端口为8000,此时,运行程序客户端将不能够调用服务,因为服务端不监听8080端口。可以用TcpTrace做个消息转发,让它监听8080端口,把任何访问8080端口的消息转发到8000端口。这样TcpTrace就有机会捕捉客户端与服务端的任何通讯消息。可以如下设置TcpTrace
程序的运行结果如下: