.NET Core 中 tcp 服务器的 IHostedService [英] IHostedService for tcp servers in .NET Core
问题描述
我正在尝试构建一个小型 tcp 服务器/守护程序,将 asp.net 核心作为 Web 前端与服务器进行交互.我发现 IHostedService/BackgroundService 似乎提供了一种将服务器和前端捆绑在一起的低成本替代方案.
I am trying to build a small tcp server/daemon with asp.net core as a web frontend to interact with the server. I have found IHostedService/BackgroundService which seems to provide a low effort alternative to bundle the server and the frontend together.
目前的代码基本上是这样的(用于测试目的的回声服务器):
The code looks basically like this at the moment (echo server for testing purposes):
public class Netcat : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
TcpListener listener = new TcpListener(IPAddress.Any, 8899);
listener.Start();
while(!stoppingToken.IsCancellationRequested)
{
TcpClient client = await listener.AcceptTcpClientAsync();
NetworkStream stream = client.GetStream();
while (!stoppingToken.IsCancellationRequested)
{
byte[] data = new byte[1024];
int read = await stream.ReadAsync(data, 0, 1024, stoppingToken);
await stream.WriteAsync(data, 0, read, stoppingToken);
}
}
}
}
并在 Startup.cs 中像这样初始化:
And is initialized in Startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<Netcat>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
对于现代 Asp.Net 核心应用程序和守护程序应该如何合作,是否有共同的模式?
Is there a common pattern for how modern Asp.Net core applications and daemons should cooperate?
我将如何从控制器与正在运行的服务本身交互?
How would I interact with the running service itself from a Controller?
IHostedService 是否可用于此目的,或者它是一种将 Asp.Net 前端和服务/服务器完全解耦的更好方法,例如通过使用某种 IPC 机制将守护进程和 asp.net 作为单独的进程运行?
Is IHostedService even usable for this purpose or is it a better way that fully decouples the Asp.Net frontend and the service/server, e.g. by running the daemon and asp.net as seperate processes with some sort of IPC mechanism?
推荐答案
对于现代 Asp.Net 核心应用程序和守护程序应该如何合作,是否有共同的模式?
Is there a common pattern for how modern Asp.Net core applications and daemons should cooperate?
实际上,托管服务目前还没有那么强大.所以人们通常使用第三种产品.但是,可以与托管服务和控制器通信.我将使用您的代码作为示例来实现这些目标:
Actually , the hosted service is not that powerful for the present . So people usually use a third product . However , it's possible to communicate with hosted service and controller . I'll use your code as an example to achieve these goals :
TcpServer
能够接收两个命令,以便我们可以从TcpClient
切换托管服务的状态.WebServer
的控制器可以间接(通过中介)调用TcpServer
的方法,并将其呈现为 html
- The
TcpServer
is able to receive two commands so that we can switch the state of hosted service from aTcpClient
. - The controller of
WebServer
can invoke method ofTcpServer
indirectly (through a mediator ), and render it as html
将控制器与托管服务耦合不是一个好主意.为了从托管服务调用方法,我们可以引入一个 Mediator.中介者只不过是作为单例的服务(因为它将被托管服务引用):
It's not a good idea to couple controller with hosted service . To invoke method from hosted service , we can introduce a Mediator . A mediator is no more than a service that serves as a singleton (because it will referenced by hosted service) :
public interface IMediator{
event ExecHandler ExecHandler ;
string Exec1(string status);
string Exec2(int status);
// ...
}
public class Mediator: IMediator{
public event ExecHandler ExecHandler ;
public string Exec1(string status)
{
if(this.ExecHandler==null)
return null;
return this.ExecHandler(status);
}
public string Exec2(int status)
{
throw new System.NotImplementedException();
}
}
托管服务需要意识到IMediator
的存在,并以某种方式将其方法暴露给IMediator
:
A Hosted Service needs to realize the existence of IMediator
and expose his method to IMediator
in some way :
public class Netcat : BackgroundService
{
private IMediator Mediator ;
public Netcat(IMediator mediator){
this.Mediator=mediator;
}
// method that you want to be invoke from somewhere else
public string Hello(string status){
return $"{status}:returned from service";
}
// method required by `BackgroundService`
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
TcpListener listener = new TcpListener(IPAddress.Any, 8899);
listener.Start();
while(!stoppingToken.IsCancellationRequested)
{
// ...
}
}
}
为了允许从 NetCat TcpServer
控制状态,我让它能够从客户端接收两个命令来切换后台服务的状态:
To allow control the status from the NetCat TcpServer
, I make it able to receive two commands from clients to switch the state of background service :
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
TcpListener listener = new TcpListener(IPAddress.Any, 8899);
listener.Start();
while(!stoppingToken.IsCancellationRequested)
{
TcpClient client = await listener.AcceptTcpClientAsync();
Console.WriteLine("a new client connected");
NetworkStream stream = client.GetStream();
while (!stoppingToken.IsCancellationRequested)
{
byte[] data = new byte[1024];
int read = await stream.ReadAsync(data, 0, 1024, stoppingToken);
var cmd= Encoding.UTF8.GetString(data,0,read);
Console.WriteLine($"[+] received : {cmd}");
if(cmd=="attach") {
this.Mediator.ExecHandler+=this.Hello;
Console.WriteLine($"[-] exec : attached");
continue;
}
if(cmd=="detach") {
Console.WriteLine($"[-] exec : detached");
this.Mediator.ExecHandler-=this.Hello;
continue;
}
await stream.WriteAsync(data, 0, read, stoppingToken);
stream.Flush();
}
}
}
如果你想在控制器中调用后台服务的方法,只需注入IMediator
:
If you want to invoke the method of background service within a controller, simply inject
the IMediator
:
public class HomeController : Controller
{
private IMediator Mediator{ get; }
public HomeController(IMediator mediator){
this.Mediator= mediator;
}
public IActionResult About()
{
ViewData["Message"] = this.Mediator.Exec1("hello world from controller")??"nothing from hosted service";
return View();
}
}
这篇关于.NET Core 中 tcp 服务器的 IHostedService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!