我正在尝试在与第三方应用程序通信的wcf服务中托管TCP客户端连接。 WCF服务将tcp调用包装到第三方应用程序,以便连接到WCF服务的任何应用程序都不知道TCP连接。由于第三方应用程序需要的协议,tcp连接必须保持活动状态。我已经实现了处理错误和重新连接的逻辑,但是我遇到的问题是如何打开和关闭此连接。有没有办法让我重写主机打开和关闭的呼叫,以便我可以对我的CommunicationService做同样的事情?TCP Keep Alive连接托管在WCF中
我的代码:
public partial class HostService : ServiceBase
{
private ServiceHost _host;
public HostService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Type serviceType = typeof(MessageProcessor);
var serviceUri = new Uri("http://localhost:9091/");
_host = new ServiceHost(serviceType, serviceUri);
_host.Open();
}
protected override void OnStop()
{
_host.Close();
}
}
[ServiceContract]
public interface IMessageProcessor
{
[OperationContract]
void ProcessMessage(string message);
}
public class MessageProcessor : IMessageProcessor
{
//This is handling my TCP connection.
private CommunicationService _communicationService;
public MessageProcessor()
{
_communicationService = new CommunicationService();
}
public void ProcessMessage(string message)
{
if(_communicationService.Connected)
{
var request = new QueryMessage();
var result = _communicationService.TransmitMessage(request);
}
else
{
//Error handling, not necessary for now
}
}
//I want to do this
public override Open()
{
_communicationService.Open();
}
public override Close()
{
_communicationService.Close();
}
}
当两个客户端(因此两个线程)试图同时调用您的ProcessMessage方法(原则上是您的TCP连接)时,您会发生什么? – 2012-03-27 14:42:12
你使用什么InstanceContextMode来为你的服务?这将大大决定MessageProcessor的生命周期和潜在多个实例。 – GazTheDestroyer 2012-03-27 15:06:01
KirkWoll,我的通信类中有逻辑来处理多线程。我排队消息并根据其类型给予优先级。 GazTheDestroyer,恐怕我不确定你指的是什么,这是我第一次使用WCF。我在做什么不理想?有一个更好的方法吗? – jtiger 2012-03-27 17:13:18