在 .net core 控制台应用程序中创建一个 websocket 服务器 [英] Create a websocket server in .net core console application
问题描述
有什么方法可以创建一个可以托管 WebSocket 服务器的 .NET Core 控制台应用程序?
Is there any way to create a .NET Core console application which can host a WebSocket server?
我看到了很多东西,但只用于 ASP.NET Core 依赖注入.
I see a lot of stuff but only for using with ASP.NET Core dependency injection.
我最终使用的 NuGet 包必须是 .NET Core 而不是完整的 .NET.
The NuGet package I end up using must be .NET Core and not full .NET.
如果我可以在控制台应用程序中使用 Microsoft.AspNetCore.WebSockets
,我会怎么做?
If I can use Microsoft.AspNetCore.WebSockets
in a console application, how would I do it?
推荐答案
自托管 ASP.net Core 应用程序实际上是控制台应用程序,使用 Kestrel 作为服务器,您可以非阻塞地运行它并继续程序作为常规控制台一,类似这样:
Self-hosted ASP.net Core applications are in fact console applications, using Kestrel as the server you can run it in non-blocking and continue the program as a regular console one, something like this:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.Build(); //Modify the building per your needs
host.Start(); //Start server non-blocking
//Regular console code
while (true)
{
Console.WriteLine(Console.ReadLine());
}
}
唯一的缺点是您会在开始时收到一些调试消息,但您可以通过此修改来抑制这些消息:
The only downside of this is you will get some debug messages at the begining, but you can supress those with this modification:
public static void Main(string[] args)
{
ConsOut = Console.Out; //Save the reference to the old out value (The terminal)
Console.SetOut(new StreamWriter(Stream.Null)); //Remove console output
var host = new WebHostBuilder()
.UseKestrel()
.Build(); //Modify the building per your needs
host.Start(); //Start server non-blocking
Console.SetOut(ConsOut); //Restore output
//Regular console code
while (true)
{
Console.WriteLine(Console.ReadLine());
}
}
这篇关于在 .net core 控制台应用程序中创建一个 websocket 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!