1.mqtt.net在调试时,发现工具订阅topic不上
2.调试后发现,在订阅第1台时,可及时响应订阅事件,但后面那台,并没有响应到Subscribed这个事件中来
3.后面那台发送一直是正常的,运行的客户端有收到发布的消息。但MQTT服务运行后,用工具就订阅不上
static IMqttServer mqttServer;
try
{
mqttServer = new MqttFactory().CreateMqttServer();
MqttServerOptionsBuilder builder = new MqttServerOptionsBuilder()
// .WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Any)//配置IP
.WithDefaultEndpointBoundIPAddress(Dns.GetHostAddresses(192.168.0.11)
.WithDefaultEndpointPort(1883)
.WithConnectionValidator(context =>
{
if (context.Username == "admin" && context.Password == "123456")
{
context.ReasonCode = MQTTnet.Protocol.MqttConnectReasonCode.Success;
}
else
{
context.ReasonCode = MQTTnet.Protocol.MqttConnectReasonCode.BadUserNameOrPassword;
}
});
IMqttServerOptions options = builder.Build();
mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(Server_ClientConnected);
////服务启动事件
mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(async (args) =>
{
// await Started(mqttServer, args);
});
////服务停止事件
mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(_mqttServer_StoppedAsync);
////客户端连接事件
//server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(Connected);
mqttServer.ApplicationMessageReceivedHandler =
new MqttApplicationMessageReceivedHandlerDelegate(Server_ApplicationMessageReceived);
////客户端订阅Topic
mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(Subscribed);
////客户端断开事件
mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(Server_Disconnected);
////客户端取消订阅Topic
mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(_mqttServer_ClientUnsubscribedTopicAsync);
await mqttServer.StartAsync(options);
//while (!stoppingToken.IsCancellationRequested)
//{
// _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
// await Task.Delay(1000, stoppingToken);
//}
}
catch (Exception ex)
{
Console.WriteLine("服务启动失败,请检查IP配置!" + ex.Message);
NLogHelper.Error(ex.Message);
Thread.Sleep(1000);
_hostApplicationLifetime.StopApplication(); //手动调用 StopApplication
}
/// <summary>
/// 客户端订阅Topic
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
static async Task Subscribed(MqttServerClientSubscribedTopicEventArgs args)
{
try
{
Console.WriteLine($"{DateTime.Now.ToString()} 客户端【{args.ClientId}】订阅Topic {args.TopicFilter.Topic}");
}
catch (Exception e)
{
Console.WriteLine($"{DateTime.Now.ToString()} 客户端【{args.ClientId}】订阅Topic{args.TopicFilter.Topic}异常 ");
Console.WriteLine(e);
}
}