【发布时间】:2020-06-23 19:42:47
【问题描述】:
我有一个运行某些任务的 Windows 服务。我需要在其任务列表中添加一些网络功能。
网络逻辑如下所示:
+-------------------+ +---------------+
| | send request | |
| | for some data | |
| | <--------------------------------------------- | |
| | | |
| | process request | Client |
| Windows Service | | Application |
| | send response | |
| | ---------------------------------------------> | |
| | | |
| | process response | |
+-------------------+ +---------------+
注意:可以有多个客户端应用程序同时请求数据。
注意:每个客户端应用程序可以同时发送多个数据请求。
注意:Windows 服务和客户端应用程序可以驻留在同一网络或不同的网络中。
这是 Windows 服务的基本布局:
class Processor : System.ServiceProcess.ServiceBase
{
private System.Timers.Timer Timer1 = null;
private System.Timers.Timer Timer2 = null;
private System.Timers.Timer Timer3 = null;
protected override void OnStart(string[] args)
{
Timer1 = new System.Timers.Timer();
Timer1.Interval = ...;
Timer1.AutoReset = true;
Timer1.Elapsed += new ElapsedEventHandler(...);
Timer1.Start();
Timer2 = new System.Timers.Timer();
Timer2.Interval = ...;
Timer2.AutoReset = true;
Timer2.Elapsed += new ElapsedEventHandler(...);
Timer2.Start();
Timer3 = new System.Timers.Timer();
Timer3.Interval = ...;
Timer3.AutoReset = true;
Timer3.Elapsed += new ElapsedEventHandler(...);
Timer3.Start();
// I was thinking of creating a new Task (System.Threading.Tasks.Task) or Timer (System.Timers.Timer) here to handle the networking-related logic.
}
protected override void OnStop()
{
Timer1.Stop();
Timer1.Close();
Timer2.Stop();
Timer2.Close();
Timer3.Stop();
Timer3.Close();
}
}
我一直在阅读微软的网络编程documentation,但我仍然不知道哪个课程最适合我的情况。
我一直在考虑使用的类是:
- Socket
- TcpListener(用于 Windows 服务)和TcpClient(用于客户端应用程序)
- HttpListener(用于 Windows 服务)和HttpClient(用于客户端应用程序)
TcpListener 和 TcpClient 类是 Socket 类的包装器。它们似乎隐藏了许多实现细节并使代码更易于理解。 Socket 类提供的功能数量似乎相当庞大,但它可以处理multiple client connections。 TcpListener 可以处理多个客户端还是一次只能监听一个?
哪种网络课程最适合我的情况?我如何保证请求将以响应的方式提供服务,同时又保证与网络无关的任务将继续执行而不会被阻塞?
【问题讨论】:
-
我喜欢你的问题..但它已经加载,所以我只是给你我的初步想法......我会考虑使用 Windows Communication Foundation,它可以让你做任何你想做的事,并且以强类型的方式。至于阻塞,请确保所有网络内容都是异步的。
-
当您说“确保所有网络内容都是异步的”时,在单独的线程/任务/计时器中生成“网络对象”(无论它可能是什么)就足够了吗?
-
我只是将异步作为一个一般概念(线程、回调,任何有意义的东西)。这很可能涉及 .NET 中的
async/await和Tasks。例如TcpClient,有一个Connect方法和一个ConnectAsync方法,如果这是你选择的方向,你可能会更喜欢后者。
标签: c# sockets networking .net-core tcp