使用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的性能

单个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<IManagedMqttClient> managedMqttClients = new List<IManagedMqttClient>(); 

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} ");
};

运行效果图:

 


  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值