且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 .net core 控制台应用程序中创建一个 websocket 服务器

更新时间:2023-02-19 18:42:57

自托管 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());
    }
}

有关控制台输出的来源.