Search code examples
c#asp.net-coretcpkestrel-http-server

(How) Can I use ASP.NET Core for custom TCP packet communication?


I have a dated game server with typical TCP packet protocol (length / type / data[length]), and my task is to find modern frameworks to rewrite it in.

Having written a (small) RESTish API in ASP.NET Core 2.1, I know that it provides DI / logging / configuration features which could perfectly replace similar functionality in the old server. I thought I could use ASP.NET Core, making it handle said TCP packets instead of HTTP requests.

Now I'm a bit stuck in where to start and if / how it would fit into ASP.NET Core. So far I've RTFM'ed about inner ASP.NET Core workings and found some things that confused me:

  • Official docs state Kestrel only supports HTTP based scenarios (don't wanna use IIS). So does the tag here on SO.
  • Then I found a project claiming to add TCP support to Kestrel, yet I don't fully understand how it's done. It seems to be done by implementing a ConnectionHandler, but I can't see, for example, where it starts a TcpListener to accept new continuous connections with clients.
  • With Kestrel seemingly out of the question, I thought about writing an IHostedService or BackgroundService to do all TCP communication in.
  • Then I didn't know if I could use Middleware to pipe my TCP packets through (thought of an authorization and game logic middleware). Official docs quickly talk about HTTP or "web" requests, so I thought a typical middleware pipeline is out of the question too.

To sum it up, my research resulted in the following two questions:

  • Can I actually use Kestrel for continuous TCP connections with binary communication?
  • What is the relation between the middleware pipeline and HTTP functionality / Kestrel? Can I use a middleware pipeline in custom services for TCP communication?

Solution

  • After getting back to this, I realized that Project Bedrock is aiming to further generalize Kestrel to support completely custom protocols, not even limited to raw TCP. An overview / description can be found here.

    The link above shows the current public state of the project on the GitHub repository with great practical examples. It seems to be planned to be integrated with whatever follows the ASP.NET Core roadmap for .NET 6, but a prerelease version compatible with .NET Core 3.1 is available and works great in my experiments. The functionality in question no longer seems to be on the roadmap.