使用MQTTnet连接Mqtt服务器

https://blog.csdn.net/weixin_42930928/article/details/82383297

上篇文章介绍了mqttnet的内容,并使用mqttnet搭建了一个mqtt服务器。本篇文章将继续使用mqttnet做一个客户端,用于连接mqtt服务器。

client的界面部署入下图所示,

1、单个mqtt client,可是使用订阅主题和发布主题,

2、创建多个mqtt client,测试mqtt server的性能

使用MQTTnet连接Mqtt服务器_第1张图片

单个mqtt client连接服务器

添加了客户端连接,断开和消息到达的事件

private async void MqttClient()
{
    try
    {
		var options = new MqttClientOptions() {ClientId = Guid.NewGuid().ToString("D")};
		options.ChannelOptions = new MqttClientTcpOptions()
		{
			Server = TxbServer.Text,
			Port = Convert.ToInt32(TxbPort.Text)
		};
		options.Credentials = new MqttClientCredentials()
		{
			Username = "admin",
			Password = "public"
		};

		options.CleanSession = true;
		options.KeepAlivePeriod = TimeSpan.FromSeconds(100.5);
		options.KeepAliveSendInterval = TimeSpan.FromSeconds(20000);

		if (null != _mqttClient)
		{
			await _mqttClient.DisconnectAsync();
			_mqttClient = null;
		}
		_mqttClient = new MqttFactory().CreateMqttClient();

		_mqttClient.ApplicationMessageReceived += (sender, args) =>
		{
			listBox1.BeginInvoke(
				_updateListBoxAction,
				$"ClientID:{args.ClientId} | TOPIC:{args.ApplicationMessage.Topic} | Payload:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)} | QoS:{args.ApplicationMessage.QualityOfServiceLevel} | Retain:{args.ApplicationMessage.Retain}"
				);
		};

		_mqttClient.Connected += (sender, args) =>
		{
			listBox1.BeginInvoke(_updateListBoxAction,
			$"Client is Connected:  IsSessionPresent:{args.IsSessionPresent}");
		};

		_mqttClient.Disconnected += (sender, args) =>
		{
			listBox1.BeginInvoke(_updateListBoxAction,
			$"Client is DisConnected ClientWasConnected:{args.ClientWasConnected}");
		};

		await _mqttClient.ConnectAsync(options);
    }
    catch (Exception)
    {
		throw;
    }
}

多个mqtt client连接服务器:

多个mqtt client的连接使用ManagedClient,

private List managedMqttClients = new List(); 

private async void MqttMultiClient( int clientsCount)
{
    await Task.Factory.StartNew(async () =>
     {
		for (int i = 0; i < clientsCount; i++)
		{
			var options = new ManagedMqttClientOptionsBuilder()
			 .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
			 .WithClientOptions(new MqttClientOptionsBuilder()
				 .WithClientId(Guid.NewGuid().ToString().Substring(0, 13))
				 .WithTcpServer(TxbServer.Text, Convert.ToInt32(TxbPort.Text))
				 .WithCredentials("admin", "public")
				 .Build()
			 )
			 .Build();

			var c = new MqttFactory().CreateManagedMqttClient();
			await c.SubscribeAsync(
				new TopicFilterBuilder().WithTopic(txbSubscribe.Text)
				.WithQualityOfServiceLevel(
		        (MqttQualityOfServiceLevel)
				Enum.Parse(typeof(MqttQualityOfServiceLevel), CmbSubMqttQuality.Text)).Build());

			 await c.StartAsync(options);

			 managedMqttClients.Add(c);

			 Thread.Sleep(200);
        }
     });
}

关于ManagedClient的介绍,官方给出了如下解释:

This project also contains a managed MQTT client. The client has some additional functionality in comparison with the regular MqttClient. Those functionalities are reflecting the most common use cases and thus the ManagedClient provides a out-of-the-box MQTT client with the following features.

  1. The managed client is started once and will maintain the connection automatically including reconnecting etc.
  2. All MQTT application messages are added to an internal queue and processed once the server is available.
  3. All MQTT application messages can be stored to support sending them after a restart of the application
  4. All subscriptions are managed across server connections. There is no need to subscribe manually after the connection with the server is lost.

 

 MqttNetGlobalLogger的使用

//MqttNetGlobalLogger的使用
MqttNetGlobalLogger.LogMessagePublished += (o, args) =>
{
    var s = new StringBuilder();
    s.Append($"{args.TraceMessage.Timestamp} ");
    s.Append($"{args.TraceMessage.Level} ");
    s.Append($"{args.TraceMessage.Source} ");
    s.Append($"{args.TraceMessage.ThreadId} ");
    s.Append($"{args.TraceMessage.Message} "); 
    s.Append($"{args.TraceMessage.Exception}");
    s.Append($"{args.TraceMessage.LogId} ");
};

运行效果图:

使用MQTTnet连接Mqtt服务器_第2张图片

 


你可能感兴趣的:(mqttnet,.Net开源类库,MQTT,.NET,开源类库)