Send and Receive Messages
This guide will walk you through the essential steps to send and receive messages using Azure Event Hubs. Event Hubs is a highly scalable data streaming platform and event ingestion service. You can use it to process millions of events per second from various sources.
Open your terminal or command prompt and run the following commands to create a new .NET console application:
dotnet new console -n EventHubsQuickstart
cd EventHubsQuickstart
Add the necessary Azure Event Hubs NuGet package:
dotnet add package Azure.Messaging.EventHubs
Replace the contents of your Program.cs file with the following code. Make sure to replace YOUR_EVENTHUB_CONNECTION_STRING and YOUR_EVENTHUB_NAME with your actual values.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
// Replace with your actual connection string and Event Hub name
const string eventHubConnectionString = "YOUR_EVENTHUB_CONNECTION_STRING";
const string eventHubName = "YOUR_EVENTHUB_NAME";
var producerClient = new EventHubProducerClient(eventHubConnectionString, eventHubName);
Console.WriteLine("Sending messages...");
try
{
using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
for (int i = 1; i <= 5; i++)
{
var message = $"Message {i}";
if (!eventBatch.TryAddMessage(new EventData(Encoding.UTF8.GetBytes(message))))
{
// The batch is full, send it and create a new one
await producerClient.SendAsync(eventBatch);
Console.WriteLine($"Sent batch with {eventBatch.Count} messages.");
// Create a new batch for the next messages
// Note: We re-create the batch for simplicity in this example.
// In a real-world scenario, you might manage batching more dynamically.
break; // Exit loop after sending first full batch for this example
}
}
// Send the last batch if it has messages
if (eventBatch.Count > 0)
{
await producerClient.SendAsync(eventBatch);
Console.WriteLine($"Sent final batch with {eventBatch.Count} messages.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
await producerClient.DisposeAsync();
}
Console.WriteLine("Messages sent. Press any key to exit.");
Console.ReadKey();
Create a separate .NET console application for the receiver (or modify your existing one to handle both sender and receiver roles, though separate projects are cleaner for quickstarts). Replace the contents of its Program.cs file with the following code. Again, use your actual connection string and Event Hub name.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Consumer;
// Replace with your actual connection string and Event Hub name
const string eventHubConnectionString = "YOUR_EVENTHUB_CONNECTION_STRING";
const string eventHubName = "YOUR_EVENTHUB_NAME";
const string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName; // Use default consumer group
var consumerClient = new EventHubConsumerClient(consumerGroup, eventHubConnectionString, eventHubName);
Console.WriteLine("Listening for messages...");
try
{
await foreach (PartitionEvent partitionEvent in consumerClient.ReadEventsAsync(CancellationToken.None))
{
string messageBody = Encoding.UTF8.GetString(partitionEvent.Data.EventBody.ToArray());
Console.WriteLine($"Received message: '{messageBody}' from partition {partitionEvent.Partition.Id}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
await consumerClient.DisposeAsync();
}
Console.WriteLine("Listener stopped. Press any key to exit.");
Console.ReadKey();
dotnet run
dotnet run
You should see the sender application outputting that it's sending messages, and the receiver application outputting the messages it receives.