├── .gitignore ├── KestrelTcpDemo.sln ├── KestrelTcpDemo ├── KestrelTcpDemo.csproj ├── MyEchoConnectionHandler.cs ├── MyFrameworkExtensions.cs ├── Program.cs └── Startup.cs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | 290 | # SQL Lite 291 | *.db 292 | 293 | # Visual Studio code 294 | .vscode/ -------------------------------------------------------------------------------- /KestrelTcpDemo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26124.0 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KestrelTcpDemo", "KestrelTcpDemo\KestrelTcpDemo.csproj", "{998D1492-BF6C-4B4B-9D45-002151E69128}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|x64 = Debug|x64 12 | Debug|x86 = Debug|x86 13 | Release|Any CPU = Release|Any CPU 14 | Release|x64 = Release|x64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Debug|x64.ActiveCfg = Debug|Any CPU 24 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Debug|x64.Build.0 = Debug|Any CPU 25 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Debug|x86.ActiveCfg = Debug|Any CPU 26 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Debug|x86.Build.0 = Debug|Any CPU 27 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Release|x64.ActiveCfg = Release|Any CPU 30 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Release|x64.Build.0 = Release|Any CPU 31 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Release|x86.ActiveCfg = Release|Any CPU 32 | {998D1492-BF6C-4B4B-9D45-002151E69128}.Release|x86.Build.0 = Release|Any CPU 33 | EndGlobalSection 34 | EndGlobal 35 | -------------------------------------------------------------------------------- /KestrelTcpDemo/KestrelTcpDemo.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp2.2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /KestrelTcpDemo/MyEchoConnectionHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNetCore.Connections; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace KestrelTcpDemo 6 | { 7 | public class MyEchoConnectionHandler : ConnectionHandler 8 | { 9 | private readonly ILogger _logger; 10 | 11 | public MyEchoConnectionHandler(ILogger logger) 12 | { 13 | _logger = logger; 14 | } 15 | 16 | public override async Task OnConnectedAsync(ConnectionContext connection) 17 | { 18 | _logger.LogInformation(connection.ConnectionId + " connected"); 19 | 20 | while (true) 21 | { 22 | var result = await connection.Transport.Input.ReadAsync(); 23 | var buffer = result.Buffer; 24 | 25 | foreach (var segment in buffer) 26 | { 27 | await connection.Transport.Output.WriteAsync(segment); 28 | } 29 | 30 | if (result.IsCompleted) 31 | { 32 | break; 33 | } 34 | 35 | connection.Transport.Input.AdvanceTo(buffer.End); 36 | } 37 | 38 | _logger.LogInformation(connection.ConnectionId + " disconnected"); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /KestrelTcpDemo/MyFrameworkExtensions.cs: -------------------------------------------------------------------------------- 1 | // This shows how a framework would implement a custom connection handler 2 | 3 | using System; 4 | using System.Buffers; 5 | using System.Net; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNetCore.Connections; 8 | using Microsoft.AspNetCore.Server.Kestrel.Core; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.DependencyInjection.Extensions; 11 | using Microsoft.Extensions.Options; 12 | 13 | namespace KestrelTcpDemo 14 | { 15 | public static class MyFrameworkExtensions 16 | { 17 | public static IServiceCollection AddFramework(this IServiceCollection services, IPEndPoint endPoint) 18 | { 19 | services.TryAddEnumerable(ServiceDescriptor.Singleton, MyFrameworkOptionsSetup>()); 20 | 21 | services.Configure(o => 22 | { 23 | o.EndPoint = endPoint; 24 | }); 25 | 26 | services.TryAddSingleton(); 27 | return services; 28 | } 29 | } 30 | 31 | public class MyFrameworkOptionsSetup : IConfigureOptions 32 | { 33 | private readonly MyFrameworkOptions _options; 34 | 35 | public MyFrameworkOptionsSetup(IOptions options) 36 | { 37 | _options = options.Value; 38 | } 39 | 40 | public void Configure(KestrelServerOptions options) 41 | { 42 | options.Listen(_options.EndPoint, builder => 43 | { 44 | builder.UseConnectionHandler(); 45 | }); 46 | } 47 | 48 | // This is the connection handler the framework uses to handle new incoming connections 49 | private class MyFrameworkConnectionHandler : ConnectionHandler 50 | { 51 | private readonly IFrameworkMessageParser _parser; 52 | 53 | public MyFrameworkConnectionHandler(IFrameworkMessageParser parser) 54 | { 55 | _parser = parser; 56 | } 57 | 58 | public override async Task OnConnectedAsync(ConnectionContext connection) 59 | { 60 | var input = connection.Transport.Input; 61 | 62 | // Code to parse framework messages 63 | while (true) 64 | { 65 | var result = await input.ReadAsync(); 66 | var buffer = result.Buffer; 67 | 68 | if (_parser.TryParseMessage(ref buffer, out var message)) 69 | { 70 | await ProcessMessageAsync(message); 71 | } 72 | 73 | input.AdvanceTo(buffer.Start, buffer.End); 74 | } 75 | } 76 | 77 | private Task ProcessMessageAsync(Message message) 78 | { 79 | throw new NotImplementedException(); 80 | } 81 | } 82 | } 83 | 84 | // The framework exposes options for how to bind 85 | public class MyFrameworkOptions 86 | { 87 | public IPEndPoint EndPoint { get; set; } 88 | } 89 | 90 | // The framework exposes a message parser used to parse incoming protocol messages from the network 91 | public interface IFrameworkMessageParser 92 | { 93 | bool TryParseMessage(ref ReadOnlySequence buffer, out Message message); 94 | } 95 | 96 | public class FrameworkMessageParser : IFrameworkMessageParser 97 | { 98 | public bool TryParseMessage(ref ReadOnlySequence buffer, out Message message) 99 | { 100 | // TODO: Implement logic here 101 | throw new NotImplementedException(); 102 | } 103 | } 104 | 105 | public class Message 106 | { 107 | // TODO: Add properties relevant to your message type here 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /KestrelTcpDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Microsoft.AspNetCore; 3 | using Microsoft.AspNetCore.Connections; 4 | using Microsoft.AspNetCore.Hosting; 5 | 6 | namespace KestrelTcpDemo 7 | { 8 | public class Program 9 | { 10 | public static void Main(string[] args) 11 | { 12 | CreateWebHostBuilder(args).Build().Run(); 13 | } 14 | 15 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 16 | WebHost.CreateDefaultBuilder(args) 17 | .ConfigureServices(services => 18 | { 19 | // This shows how a custom framework could plug in an experience without using Kestrel APIs directly 20 | services.AddFramework(new IPEndPoint(IPAddress.Loopback, 8009)); 21 | }) 22 | .UseKestrel(options => 23 | { 24 | // TCP 8007 25 | options.ListenLocalhost(8007, builder => 26 | { 27 | builder.UseConnectionHandler(); 28 | }); 29 | 30 | // HTTP 5000 31 | options.ListenLocalhost(5000); 32 | 33 | // HTTPS 5001 34 | options.ListenLocalhost(5001, builder => 35 | { 36 | builder.UseHttps(); 37 | }); 38 | }) 39 | .UseStartup(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /KestrelTcpDemo/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace KestrelTcpDemo 11 | { 12 | public class Startup 13 | { 14 | // This method gets called by the runtime. Use this method to add services to the container. 15 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 16 | public void ConfigureServices(IServiceCollection services) 17 | { 18 | } 19 | 20 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 21 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 22 | { 23 | if (env.IsDevelopment()) 24 | { 25 | app.UseDeveloperExceptionPage(); 26 | } 27 | 28 | app.Run(async (context) => 29 | { 30 | await context.Response.WriteAsync("Hello World!"); 31 | }); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Multi-protocol Server with ASP.NET Core and Kestrel 2 | 3 | The following sample shows how you can host a TCP server and HTTP server in the same ASP.NET Core application. The TCP server runs on port 8007 and the HTTP server runs on ports 5000 and 5001. 4 | 5 | Under the covers, it's the same server (Kestrel) running different protocols on different ports. The [ConnectionHandler](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.connections.connectionhandler?view=aspnetcore-2.1) is a new primitive introduced in ASP.NET Core 2.1 to support non-HTTP protocols. ConnectionHandlers are activated by the dependency injection system in ASP.NET Core; this means you can access any registered service in the constructor of your `ConnectionHandler`. 6 | 7 | ConnectionHandlers also provide access to the connected client via a [ConnectionContext](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.connections.connectioncontext?view=aspnetcore-2.1). The `ConnectionContext` provides information about the underlying connection (like the connection id) and it also exposes the raw data stream using an `IDuplexPipe`. The `IDuplexPipe` is a new primitive that represents a bi-directional stream using the new [System.IO.Pipelines](https://blogs.msdn.microsoft.com/dotnet/2018/07/09/system-io-pipelines-high-performance-io-in-net/) library. 8 | 9 | ## What is this really? 10 | 11 | This is part of a larger effort called Bedrock. You can read more about it [here](https://github.com/aspnet/KestrelHttpServer/issues/1980). --------------------------------------------------------------------------------