1- using Microsoft . Extensions . Configuration ;
1+ using Microsoft . Extensions . Configuration ;
22using MQTTnet ;
3+ using MQTTnet . Protocol ;
34using NBomber ;
45using NBomber . CSharp ;
56using NBomber . Data ;
@@ -16,10 +17,12 @@ public class CustomScenarioSettings
1617
1718public class ClientPoolMqttExample
1819{
20+ // For this example, please spin up local MQTT broker via docker-compose.yml located in the MQTT folder.
21+
1922 public void Run ( )
2023 {
2124 var clientPool = new ClientPool < MqttClient > ( ) ;
22- var message = Data . GenerateRandomBytes ( 200 ) ;
25+ byte [ ] payload = [ ] ;
2326
2427 var scenario = Scenario . Create ( "mqtt_scenario" , async ctx =>
2528 {
@@ -30,30 +33,32 @@ public void Run()
3033 var topic = $ "/clients/{ ctx . ScenarioInfo . InstanceId } ";
3134 var msg = new MqttApplicationMessageBuilder ( )
3235 . WithTopic ( topic )
33- . WithPayload ( message )
36+ . WithPayload ( payload )
37+ . WithQualityOfServiceLevel ( MqttQualityOfServiceLevel . AtMostOnce )
3438 . Build ( ) ;
3539
3640 return await mqttClient . Publish ( msg ) ;
3741 } ) ;
3842
3943 var receive = await Step . Run ( "receive" , ctx , async ( ) =>
40- await mqttClient . Receive ( ctx . ScenarioCancellationToken ) ) ;
44+ {
45+ var response = await mqttClient . Receive ( ctx . ScenarioCancellationToken ) ;
46+ return response ;
47+ } ) ;
4148
4249 return Response . Ok ( ) ;
4350 } )
44- . WithWarmUpDuration ( TimeSpan . FromSeconds ( 3 ) )
45- . WithLoadSimulations ( Simulation . KeepConstant ( copies : 1 , during : TimeSpan . FromSeconds ( 30 ) ) )
4651 . WithInit ( async context =>
4752 {
4853 var config = context . CustomSettings . Get < CustomScenarioSettings > ( ) ;
49- message = Data . GenerateRandomBytes ( config . MsgSizeBytes ) ;
54+ payload = Data . GenerateRandomBytes ( config . MsgSizeBytes ) ;
5055
5156 for ( var i = 0 ; i < config . ClientCount ; i ++ )
5257 {
5358 var topic = $ "/clients/mqtt_scenario_{ i } ";
5459 var clientId = $ "mqtt_client_{ i } ";
5560 var options = new MqttClientOptionsBuilder ( )
56- . WithWebSocketServer ( options => { options . WithUri ( config . MqttServerUrl ) ; } )
61+ . WithTcpServer ( config . MqttServerUrl )
5762 . WithClientId ( clientId )
5863 . Build ( ) ;
5964
@@ -62,16 +67,18 @@ public void Run()
6267
6368 if ( ! connectResult . IsError )
6469 {
65- await mqttClient . Subscribe ( topic ) ;
70+ await mqttClient . Subscribe ( topic , MqttQualityOfServiceLevel . AtMostOnce ) ;
6671 clientPool . AddClient ( mqttClient ) ;
6772 }
6873 else
6974 throw new Exception ( "client can't connect to the MQTT broker" ) ;
75+
76+ await Task . Delay ( 10 ) ;
7077 }
7178 } )
7279 . WithClean ( ctx =>
7380 {
74- clientPool . DisposeClients ( async client => await client . Disconnect ( ) ) ;
81+ clientPool . DisposeClients ( client => client . Dispose ( ) ) ;
7582 return Task . CompletedTask ;
7683 } ) ;
7784
0 commit comments