Windows侦听器服务
问题描述:
如何在c#中编写一个侦听tcp连接并处理这些连接的Windows服务?问题是我想要比主线程中的“阻塞”更好的方法,例如Windows侦听器服务
while(true) ;
我就可以开始在另一个线程监听器,但主线程需要阻塞以防止退出应用程序(和停止服务)。 谢谢。
答
最好的可能是使用ManualResetEvent
,它会阻止,直到你发出信号。
答
为什么你不使用WCF服务? - 你可以在一个窗口服务主机WCF服务....然后你可以使用NetTcpBinding的(为了通过TCP通信) 所以我们的代码是这样
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
internal static ServiceHost myServiceHost = null;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (myServiceHost != null)
{
myServiceHost.Close();
}
myServiceHost = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
myServiceHost.Open();
}
protected override void OnStop()
{
if (myServiceHost != null)
{
myServiceHost.Close();
myServiceHost = null;
}
}
}
}
下面是一些样本: http://www.pluralsight.com/community/blogs/aaron/archive/2008/12/02/screencast-hosting-wcf-services-in-windows-services.aspx http://msdn.microsoft.com/en-us/library/ms733069.aspx
答
如果你不使用WCF,那么TcpListner是要走的路。
随着您继续使用此Windows服务,您将需要某种类型的“心跳”来验证服务仍在运行。最简单的方法是定时器(比如每分钟一次)更新一个数据库。这有助于保持服务“活跃”。
同意100%。这是WCF的工作。我希望我能给你+2。一个用于建议WCF,另一个用于建立良好的链接。 – Vadim 2009-05-25 13:19:18