初始化
This commit is contained in:
92
iotweb/Program.cs
Normal file
92
iotweb/Program.cs
Normal file
@@ -0,0 +1,92 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user