我有一个简单的2控制台应用程序,该应用程序使用System.Net.Mqtt.Server -Version 0.5.42-beta
和System.Net.Mqtt-Version 0.5.42-beta
软件包进行通讯。有时客户端没有收到消息。但是我正在使用Qos.ExactlyOnce
在这里是什么问题?
有什么建议吗?
mqtt服务器具有专用客户端,该客户端负责向客户端发送消息
class Program
{
static void Main(string[] args)
{
Task.Run(() => testAsync()).GetAwaiter();
Console.ReadLine();
}
private static async Task testAsync()
{
var configuration = new MqttConfiguration();
IMqttServer mqttServer = MqttServer.Create(configuration);
mqttServer.ClientConnected += MqttServer_ClientConnected;
mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;
mqttServer.MessageUndelivered += MqttServer_MessageUndelivered;
mqttServer.Stopped += MqttServer_Stopped;
mqttServer.Start();
var client = mqttServer.CreateClientAsync().GetAwaiter().GetResult();
while (true)
{
Console.WriteLine("1- send message");
string key = Console.ReadLine();
await client.PublishAsync(new MqttApplicationMessage("topic", Encoding.ASCII.GetBytes(key)), MqttQualityOfService.ExactlyOnce, true);
Console.WriteLine($"send msg : {key} , topic : topic");
}
}
private static void MqttServer_Stopped(object sender, MqttEndpointDisconnected e)
{
}
private static void MqttServer_MessageUndelivered(object sender, MqttUndeliveredMessage e)
{
if(e.Message.Payload != null)
{
string message = Encoding.ASCII.GetString(e.Message.Payload);
Console.WriteLine($"Received message: {message}, from : {e.SenderId}");
}
}
private static void MqttServer_ClientDisconnected(object sender, string e)
{
Console.WriteLine("A user disconnected.");
}
private static void MqttServer_ClientConnected(object sender, string e)
{
Console.WriteLine("A user connected.");
}
}
mqtt客户端只是获取消息并显示在控制台上。
class Program
{
static void Main(string[] args)
{
Task.Run(() => test()).GetAwaiter();
Console.ReadLine();
}
static async void test()
{
try
{
var configuration = new MqttConfiguration();
configuration.MaximumQualityOfService = MqttQualityOfService.ExactlyOnce;
var client = await MqttClient.CreateAsync("172.16.71.188", configuration);
await client.ConnectAsync(new MqttClientCredentials("testUser"));
await client.SubscribeAsync("topic", MqttQualityOfService.ExactlyOnce);
while (true)
{
using (client.MessageStream.Subscribe(asd => Console.WriteLine($"topic: {asd.Topic}, msg: {Encoding.ASCII.GetString(asd.Payload)}")))
{
}
}
}
catch (Exception ex)
{
}
}