And*_*ndy 6 c# websocket .net-core asp.net-core
有什么方法可以创建可以承载WebSocket服务器的.NET Core 控制台应用程序?
我看到了很多东西,但仅用于与ASP.NET Core依赖项注入一起使用。
我最终使用的NuGet软件包必须是.NET Core,而不是完整的.NET。
如果可以Microsoft.AspNetCore.WebSockets在控制台应用程序中使用,该怎么办?
自托管 ASP.net Core 应用程序实际上是控制台应用程序,使用 Kestrel 作为服务器,您可以以非阻塞方式运行它,并像常规控制台一样继续运行程序,如下所示:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的缺点是您会在开始时收到一些调试消息,但您可以通过此修改来抑制这些消息:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5420 次 |
| 最近记录: |