Server_Asp_Net_Samples.cs 3.6 KB
Newer Older
C
Christian 已提交
1 2 3 4 5 6 7
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming
C
Christian 已提交
8 9
// ReSharper disable EmptyConstructor
// ReSharper disable MemberCanBeMadeStatic.Local
C
Christian 已提交
10 11 12 13 14 15

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MQTTnet.AspNetCore;
C
Christian 已提交
16
using MQTTnet.Server;
C
Christian 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

namespace MQTTnet.Samples.Server;

public static class Server_Asp_Net_Samples
{
    public static Task Start_Server_With_WebSockets_Support()
    {
        /*
         * This sample starts a minimal ASP.NET Webserver including a hosted MQTT server.
         */
        var host = Host.CreateDefaultBuilder(Array.Empty<string>())
            .ConfigureWebHostDefaults(
                webBuilder =>
                {
                    webBuilder.UseKestrel(
                        o =>
                        {
                            // This will allow MQTT connections based on TCP port 1883.
                            o.ListenAnyIP(1883, l => l.UseMqtt());
C
Christian 已提交
36

C
Christian 已提交
37 38 39 40 41 42 43 44 45 46 47
                            // This will allow MQTT connections based on HTTP WebSockets with URI "localhost:5000/mqtt"
                            // See code below for URI configuration.
                            o.ListenAnyIP(5000); // Default HTTP pipeline
                        });

                    webBuilder.UseStartup<Startup>();
                });

        return host.RunConsoleAsync();
    }

C
Christian 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    sealed class MqttController
    {
        public MqttController()
        {
            // Inject other services via constructor.
        }
        
        public Task OnClientConnected(ClientConnectedEventArgs eventArgs)
        {
            Console.WriteLine($"Client '{eventArgs.ClientId}' connected.");
            return Task.CompletedTask;
        }


        public Task ValidateConnection(ValidatingConnectionEventArgs eventArgs)
        {
            Console.WriteLine($"Client '{eventArgs.ClientId}' wants to connect. Accepting!");
            return Task.CompletedTask;
        }
    }

C
Christian 已提交
69 70
    sealed class Startup
    {
C
Christian 已提交
71
        public void Configure(IApplicationBuilder app, IWebHostEnvironment environment, MqttController mqttController)
C
Christian 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        {
            app.UseRouting();

            app.UseEndpoints(
                endpoints =>
                {
                    endpoints.MapConnectionHandler<MqttConnectionHandler>(
                        "/mqtt",
                        httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
                            protocolList => protocolList.FirstOrDefault() ?? string.Empty);
                });

            app.UseMqttServer(
                server =>
                {
                    /*
                     * Attach event handlers etc. if required.
                     */

C
Christian 已提交
91 92
                    server.ValidatingConnectionAsync += mqttController.ValidateConnection;
                    server.ClientConnectedAsync += mqttController.OnClientConnected;
C
Christian 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105
                });
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHostedMqttServer(
                optionsBuilder =>
                {
                    optionsBuilder.WithDefaultEndpoint();
                });

            services.AddMqttConnectionHandler();
            services.AddConnections();
C
Christian 已提交
106 107

            services.AddSingleton<MqttController>();
C
Christian 已提交
108 109 110
        }
    }
}