在.net核心控制台应用程序中创建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?
我看到了很多东西
我最终使用的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核心控制台应用程序中创建Websocket服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!