1
- using Microsoft . Extensions . Configuration ;
1
+ using Microsoft . Extensions . Configuration ;
2
2
using MQTTnet ;
3
3
using NBomber ;
4
4
using NBomber . CSharp ;
@@ -16,10 +16,12 @@ public class CustomScenarioSettings
16
16
17
17
public class ClientPoolMqttExample
18
18
{
19
+ // For this example, please spin up local MQTT broker via docker-compose.yml located in the MQTT folder.
20
+
19
21
public void Run ( )
20
22
{
21
23
var clientPool = new ClientPool < MqttClient > ( ) ;
22
- var message = Data . GenerateRandomBytes ( 200 ) ;
24
+ byte [ ] payload = [ ] ;
23
25
24
26
var scenario = Scenario . Create ( "mqtt_scenario" , async ctx =>
25
27
{
@@ -30,23 +32,24 @@ public void Run()
30
32
var topic = $ "/clients/{ ctx . ScenarioInfo . InstanceId } ";
31
33
var msg = new MqttApplicationMessageBuilder ( )
32
34
. WithTopic ( topic )
33
- . WithPayload ( message )
35
+ . WithPayload ( payload )
34
36
. Build ( ) ;
35
37
36
38
return await mqttClient . Publish ( msg ) ;
37
39
} ) ;
38
40
39
41
var receive = await Step . Run ( "receive" , ctx , async ( ) =>
40
- await mqttClient . Receive ( ctx . ScenarioCancellationToken ) ) ;
42
+ {
43
+ var response = await mqttClient . Receive ( ctx . ScenarioCancellationToken ) ;
44
+ return response ;
45
+ } ) ;
41
46
42
47
return Response . Ok ( ) ;
43
48
} )
44
- . WithWarmUpDuration ( TimeSpan . FromSeconds ( 3 ) )
45
- . WithLoadSimulations ( Simulation . KeepConstant ( copies : 1 , during : TimeSpan . FromSeconds ( 30 ) ) )
46
49
. WithInit ( async context =>
47
50
{
48
51
var config = context . CustomSettings . Get < CustomScenarioSettings > ( ) ;
49
- message = Data . GenerateRandomBytes ( config . MsgSizeBytes ) ;
52
+ payload = Data . GenerateRandomBytes ( config . MsgSizeBytes ) ;
50
53
51
54
for ( var i = 0 ; i < config . ClientCount ; i ++ )
52
55
{
@@ -67,11 +70,13 @@ public void Run()
67
70
}
68
71
else
69
72
throw new Exception ( "client can't connect to the MQTT broker" ) ;
73
+
74
+ await Task . Delay ( 10 ) ;
70
75
}
71
76
} )
72
77
. WithClean ( ctx =>
73
78
{
74
- clientPool . DisposeClients ( async client => await client . Disconnect ( ) ) ;
79
+ clientPool . DisposeClients ( client => client . Dispose ( ) ) ;
75
80
return Task . CompletedTask ;
76
81
} ) ;
77
82
0 commit comments