我正在尝试启动一个简单的代码库,以使用本地蚊子代理测试 MQTTNet 的库实现其订阅者和发布者代码,随后通过 HiveMQ 的 WebSocket。
目前,这些代码位于本教程的 C# 控制台应用程序中,https ://www.youtube.com/watch?v=lcsnsj1yBs0&ab_channel=RishabhSharma :
发布者代码
static async Task Main(string[] args)
{
Console.WriteLine("Publisher");
var mqttFactory = new MqttFactory();
IMqttClient mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithClientId(Guid.NewGuid().ToString())
.WithTcpServer("test.mosquito.org", 1883)
//.WithWebSocketServer("broker.hivemq.com:8000/mqtt")
.WithCleanSession()
.Build();
mqttClient.UseConnectedHandler(e =>
{
Console.WriteLine("Connected to the Broker Succesfully");
});
mqttClient.UseDisconnectedHandler(e =>
{
Console.WriteLine("Disconnected to the Broker Succesfully");
});
await mqttClient.ConnectAsync(mqttClientOptions);
Console.WriteLine("Press a key to publish the message");
Console.ReadLine();
await PublishMessageAsyn(mqttClient);
await mqttClient.DisconnectAsync();
}
private static async Task PublishMessageAsyn(IMqttClient mqttClient)
{
string messagePayload = "Hello!";
var publishMessage = new MqttApplicationMessageBuilder()
.WithTopic("astar/vfarmproject")
.WithPayload(messagePayload)
.WithAtLeastOnceQoS()
.Build();
if (mqttClient.IsConnected)
{
await mqttClient.PublishAsync(messagePayload);
Console.WriteLine($"Published Message - {messagePayload}");
}
}
订户代码
static async Task Main(string[] args)
{
Console.WriteLine("Subscriber");
var mqttFactory = new MqttFactory();
IMqttClient mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithClientId(Guid.NewGuid().ToString())
.WithTcpServer("test.mosquito.org", 1883)
//.WithWebSocketServer("broker.hivemq.com:8000/mqtt")
.WithCleanSession()
.Build();
mqttClient.UseConnectedHandler(async e =>
{
Console.WriteLine("Connected to the Broker Succesfully");
var topicFilter = new TopicFilterBuilder()
.WithTopic("astar/vfarmproject")
.Build();
await mqttClient.SubscribeAsync(topicFilter);
});
mqttClient.UseDisconnectedHandler(e =>
{
Console.WriteLine("Disconnected to the Broker Succesfully");
});
mqttClient.UseApplicationMessageReceivedHandler(e =>
{
Console.WriteLine($"Received Message - {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
});
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
Console.ReadLine();
await mqttClient.DisconnectAsync();
}
尝试await mqttClient.ConnectAsync(mqttClientOptions);
使用以下堆栈跟踪执行时引发异常:
Exception thrown: 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' in System.Private.CoreLib.dll
An exception of type 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' occurred in System.Private.CoreLib.dll but was not handled in user code