Files
Web_IoTBase_Sever_Prod/iotweb/Program.cs

93 lines
2.6 KiB
C#
Raw Normal View History

2025-12-11 14:04:39 +08:00
using Microsoft.AspNetCore.Http.Connections;
using MQTTnet.AspNetCore;
using MQTTnet.Server;
namespace iotweb
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseKestrel(o =>
{
o.ListenAnyIP(1883, l => l.UseMqtt());
o.ListenAnyIP(5000);
});
builder.Services.AddMqttServer(optionsBuilder =>
{
optionsBuilder.WithDefaultEndpoint();
});
builder.Services.AddMqttConnectionHandler();
builder.Services.AddConnections();
builder.Services.AddSingleton<MqttController>();
builder.Services.AddControllers();
var app = builder.Build();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints((endpoints) =>
{
endpoints.MapConnectionHandler<MqttConnectionHandler>("/mqtt", ConfigureWebSocketOptions);
});
app.UseMqttServer(
server =>
{
server.ValidatingConnectionAsync += Server_ValidatingConnectionAsync; ;
server.ClientConnectedAsync += Server_ClientConnectedAsync;
});
app.MapControllers();
app.Run();
}
private static void ConfigureWebSocketOptions(HttpConnectionDispatcherOptions options)
{
options.WebSockets.SubProtocolSelector = new Func<IList<string>, string>((IList<string> protocols) =>
{
return protocols.FirstOrDefault() ?? "mqtt";
});
}
private static Task Server_ClientConnectedAsync(ClientConnectedEventArgs arg)
{
return Task.CompletedTask;
}
private static Task Server_ValidatingConnectionAsync(ValidatingConnectionEventArgs arg)
{
Console.WriteLine(arg.ClientId);
return Task.CompletedTask;
}
}
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;
}
}
}