-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathProgram.cs
76 lines (65 loc) · 2.48 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
namespace SubscriberWithEvents;
using System.Text;
using System.Text.Json;
using HiveMQtt.Client;
using HiveMQtt.Client.Options;
using HiveMQtt.MQTT5.Types;
public class Program
{
public static bool ExitRequested { get; set; }
public static int MessageCount { get; set; }
public static int PublishesReceivedCount { get; set; }
public static async Task Main(string[] args)
{
MessageCount = 0;
PublishesReceivedCount = 0;
// Subscribe to the CancelKeyPress event
Console.CancelKeyPress += (sender, e) =>
{
// Handle Ctrl+C (SIGINT) by setting exitRequested flag
e.Cancel = true; // Prevent process termination
ExitRequested = true;
Console.WriteLine("Ctrl+C (SIGINT) received. Press Ctrl+C again to exit immediately.");
};
var options = new HiveMQClientOptions
{
Host = "127.0.0.1",
Port = 1883,
CleanStart = true,
ClientId = "SubscriberWithEvents",
};
var client = new HiveMQClient(options);
// Message Handler
//
// It's important that this is setup before we connect to the broker
// otherwise queued messages that are sent down may be lost.
//
client.OnMessageReceived += (sender, args) =>
{
MessageCount++;
};
// client.OnPublishReceived += (sender, args) =>
// {
// PublishesReceivedCount++;
// };
// Connect to the broker
var connectResult = await client.ConnectAsync().ConfigureAwait(false);
if (connectResult.ReasonCode != HiveMQtt.MQTT5.ReasonCodes.ConnAckReasonCode.Success)
{
throw new IOException($"Failed to connect: {connectResult.ReasonString}");
}
// Subscribe to a topic
var topic = "load/test/1";
var subscribeResult = await client.SubscribeAsync(topic, QualityOfService.ExactlyOnceDelivery).ConfigureAwait(false);
Console.WriteLine($"Subscribed to {topic}: {subscribeResult.Subscriptions[0].SubscribeReasonCode}");
var message_number = 0;
while (!ExitRequested)
{
await Task.Delay(1000).ConfigureAwait(false);
Console.WriteLine($"Received {MessageCount} msgs/sec");
// Console.WriteLine($"Received {MessageCount} msgs/sec & {PublishesReceivedCount} publishes/sec");
MessageCount = 0;
PublishesReceivedCount = 0;
}
}
}