9

Is there any way to create a .NET Core console application which can host a WebSocket server?

I see a lot of stuff but only for using with ASP.NET Core dependency injection.

The NuGet package I end up using must be .NET Core and not full .NET.

If I can use Microsoft.AspNetCore.WebSockets in a console application, how would I do it?

2
  • What about using WebClient?
    – jdweng
    Commented Jan 19, 2018 at 14:19
  • Perhaps RedHttpServer suits your needs? It wraps the AspNetCore functionality so you can create a server with 3 lines and can be installed to console applications from nuget. Disclaimer: i programmed it
    – Malte R
    Commented Jan 19, 2018 at 14:25

1 Answer 1

6

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

Source about the console output.

1
  • i like this approach -- this opens up a lot of other possibilities as well since we get a kestrel server. This is what I'm going to go with. Thanks a lot!
    – Andy
    Commented Jan 19, 2018 at 15:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.