public static class StartMqttServerMethods
{
public class MqttServerOption
{
public string HostIp { get; set; }
public int Port { get; set; }
public int TimeOut { get; set; }
public string ServerUserName { get; set; }
public string ServerPassWord { get; set; }
}
public static void AddPkspMqttServers(this IServiceCollection services, MqttServerOption mqttServerOption)
{
IMqttServer server = new MqttFactory().CreateMqttServer();
var optionBuilder = new MqttServerOptionsBuilder()
.WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse(mqttServerOption.HostIp))
.WithDefaultEndpointPort(mqttServerOption.Port)
.WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(mqttServerOption.TimeOut));
var option = optionBuilder.Build();
services.AddHostedMqttServerEx(option);
services
.AddHostedMqttServer(option)
.AddMqttConnectionHandler()
.AddMqttWebSocketServerAdapter()
.AddMqttTcpServerAdapter()
.AddConnections()
;
}
public static async void UseConnectionManager(this IMqttServer mqttServer, IApplicationBuilder app, MqttServerOption mqttServerOption)
{
var connectionManager = app.ApplicationServices.GetService<ConnectionManager>();
mqttServer.ClientConnectedHandler = connectionManager;
mqttServer.ClientDisconnectedHandler = connectionManager;
mqttServer.ClientSubscribedTopicHandler = connectionManager;
mqttServer.ClientUnsubscribedTopicHandler = connectionManager;
}
public class ConnectionManager : IMqttServerClientSubscribedTopicHandler, IMqttServerClientUnsubscribedTopicHandler, IMqttServerClientConnectedHandler, IMqttServerClientDisconnectedHandler, IMqttServerClientConnectionValidatorHandler
{
private IMqttServer mqttServer;
private IJwtUtils _jwtUtils;
private IMemoryCache _memoryCache;
public Func<MqttConnectionValidatorContext, Task> _callback;
public ConnectionManager(IMemoryCache memoryCache, IMqttServer mqttServers, IJwtUtils jwtUtils)
{
mqttServer = mqttServers;
_jwtUtils = jwtUtils;
_memoryCache = memoryCache;
}
public async Task HandleClientSubscribedTopicAsync(MqttServerClientSubscribedTopicEventArgs eventArgs)
{
}
public async Task HandleClientUnsubscribedTopicAsync(MqttServerClientUnsubscribedTopicEventArgs eventArgs)
{
await Task.Run(() =>
{
Console.WriteLine($"客户端:{eventArgs.ClientId}");
Console.WriteLine($"取消订阅主题:{eventArgs.TopicFilter}");
});
}
public async Task HandleClientDisconnectedAsync(MqttServerClientDisconnectedEventArgs eventArgs)
{
await Task.Run(() =>
{
Console.WriteLine("退出");
GC.Collect();
GC.WaitForPendingFinalizers();
});
}
public async Task HandleClientConnectedAsync(MqttServerClientConnectedEventArgs eventArgs)
{
await Task.Run(() =>
{
Console.WriteLine("连接");
});
}
public async Task HandleClientConnectionValidatorAsync(MqttServerClientConnectionValidatorEventArgs eventArgs)
{
await Task.Run(() =>
{
Console.WriteLine("进入验证");
});
}
}