| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- using System;
- using System.IO;
- using System.Reflection;
- using System.Runtime.Versioning;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.FileProviders;
- using Microsoft.Extensions.Logging;
- using MQTTnet.AspNetCore;
- using MQTTnet.Server;
- namespace MQTTnet.TestApp.AspNetCore2
- {
- public class Startup
- {
- // In class _Startup_ of the ASP.NET Core 2.0 project.
- public void ConfigureServices(IServiceCollection services)
- {
- services
- .AddHostedMqttServer(mqttServer => mqttServer.WithDefaultEndpointPort(1883)).
- AddMqttTcpServerAdapter().
- AddMqttWebSocketServerAdapter()
- .AddMqttConnectionHandler()
- .AddConnections();
- //// This adds a hosted mqtt server to the services
- //services.AddHostedMqttServer(builder => builder.WithDefaultEndpointPort(1883));
- //// This adds TCP server support based on System.Net.Socket
- //services.AddMqttTcpServerAdapter();
- //// This adds websocket support
- //services.AddMqttWebSocketServerAdapter();
- }
- // In class _Startup_ of the ASP.NET Core 3.1 project.
- #if NETCOREAPP3_1
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- app.UseRouting();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapMqtt("/mqtt");
- });
- #else
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- app.UseConnections(c => c.MapMqtt("/mqtt"));
- #endif
- app.UseMqttServer(server =>
- {
- server.StartedHandler = new MqttServerStartedHandlerDelegate(async args =>
- {
- var frameworkName = GetType().Assembly.GetCustomAttribute<TargetFrameworkAttribute>()?
- .FrameworkName;
- var msg = new MqttApplicationMessageBuilder()
- .WithPayload($"Mqtt hosted on {frameworkName} is awesome")
- .WithTopic("message");
- while (true)
- {
- try
- {
- await server.PublishAsync(msg.Build());
- msg.WithPayload($"Mqtt hosted on {frameworkName} is still awesome at {DateTime.Now}");
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- }
- finally
- {
- await Task.Delay(TimeSpan.FromSeconds(2));
- }
- }
- });
- });
-
- app.Use((context, next) =>
- {
- if (context.Request.Path == "/")
- {
- context.Request.Path = "/Index.html";
- }
- return next();
- });
- app.UseStaticFiles();
- app.UseStaticFiles(new StaticFileOptions
- {
- RequestPath = "/node_modules",
- FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
- });
- }
- }
- }
|