我正在尝试使用 MQTTnet 连接到 Mosquitto。我能够接收消息,但
IsConnected
属性是 false
。有人知道为什么吗?
仅属性 iStart
设置为 true
。
问题似乎出在 Mosquitto 主机上。
mosquitto.conf
大多是默认值。我只设置了这些参数:
allow_anonymous true
password_file C:\mosquitto\passwd
tls_version tlsv1.2
log_dest file C:\mosquitto\log\mosquitto.log
日志文件为空。
class Program
{
static async Task Main()
{
var mqttClientId = "MyClientId"; // Unique ClientId or pass a GUID as string for something random
var mqttBrokerAddress = "localhost"; // hostname or IP address of your MQTT broker
var mqttBrokerUsername = "guest"; // Broker Auth username if using auth
var mqttBrokerPassword = "guest"; // Broker Auth password if using auth
var topic = "topic"; // topic to subscribe to
var mqttClient = new MqttFactory().CreateManagedMqttClient();
var mqttClientOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithTcpServer(mqttBrokerAddress, 1883)
.WithCredentials(mqttBrokerUsername, mqttBrokerPassword) // Remove this line if no auth
.WithCleanSession().WithKeepAlivePeriod(new TimeSpan(1))//.WithTls(tlsOptions)
.Build()
)
.Build();
mqttClient.ApplicationMessageReceivedAsync += async e => MqttOnNewMessage(e);
mqttClient.ConnectedAsync += async e => MqttOnConnected(e);
mqttClient.DisconnectedAsync += async e => MqttOnDisconnected(e);
mqttClient.SynchronizingSubscriptionsFailedAsync += async e => test(e);
mqttClient.ConnectingFailedAsync += async e => test2(e);
var aaa = new List<MqttTopicFilter>();
var bbb = new MqttTopicFilterBuilder().WithTopic(topic).Build();
aaa.Add(bbb);
try
{
await mqttClient.SubscribeAsync(aaa);
await mqttClient.StartAsync(mqttClientOptions);
System.Console.WriteLine(mqttClient.IsConnected);
}
catch (Exception ex)
{
throw;
}
Console.ReadLine();
}
private static void test2(ConnectingFailedEventArgs e)
{
Console.WriteLine();
}
private static void test(ManagedProcessFailedEventArgs e)
{
Console.WriteLine();
}
private static void MqttOnNewMessage(MqttApplicationMessageReceivedEventArgs e)
{
// Do something with each incoming message from the topic
Console.WriteLine($"MQTT Client: OnNewMessage Topic: {e.ApplicationMessage.Topic} / Message: {e.ApplicationMessage.Payload}");
}
private static void MqttOnConnected(MqttClientConnectedEventArgs e) => Console.WriteLine($"MQTT Client: Connected with result: {e.ConnectResult.ResultCode}");
private static void MqttOnDisconnected(MqttClientDisconnectedEventArgs e) => Console.WriteLine($"MQTT Client: Broker connection lost with reason: {e.Reason}.");
}
问题似乎与 MQTTNet 上的保持活动属性有关。 对我来说,它通过设置
得到了修复.WithKeepAlivePeriod(时间)
我的
属性MqttClientOptionBuilder()
时间跨度为 60 瑞典克朗
var 时间 = TimeSpan.FromSeconds(60);
这就是我可以为 MqttNet github 的问题收集的内容: https://github.com/dotnet/MQTTnet/issues/1290#issuecomment-968064210