Send and Receive Events with Azure Event Hubs

This quickstart guides you through sending and receiving events from an Azure Event Hub using a simple console application. Event Hubs is a big data streaming platform and event ingestion service. It can receive and process millions of events per second.

Prerequisites:

1. Create an Event Hubs Project

We'll use .NET for this example, but similar concepts apply to other languages and SDKs.

Using .NET (C#)

Create a new console application:

dotnet new console -o EventHubsSenderReceiver

Navigate into the project directory:

cd EventHubsSenderReceiver

2. Install Event Hubs SDK

Add the Azure Event Hubs SDK package to your project.

Using .NET (C#)

dotnet add package Azure.Messaging.EventHubs

3. Write the Sender and Receiver Code

Replace the contents of your Program.cs file with the following code. Make sure to replace YOUR_EVENTHUB_CONNECTION_STRING with your actual Event Hub connection string.


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using Azure.Messaging.EventHubs.Consumer;

namespace EventHubsSenderReceiver
{
    class Program
    {
        // Replace with your Event Hub connection string
        private const string connectionString = "YOUR_EVENTHUB_CONNECTION_STRING";
        // Replace with your Event Hub name (if different from the default)
        private const string eventHubName = "my-eventhub";

        static async Task Main(string[] args)
        {
            Console.WriteLine("Azure Event Hubs Sender and Receiver Quickstart");
            Console.WriteLine("--------------------------------------------");

            // Start the sender and receiver tasks concurrently
            await Task.WhenAll(
                SendMessagesAsync(),
                ReceiveMessagesAsync()
            );

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }

        // Sends a batch of messages to the Event Hub
        static async Task SendMessagesAsync()
        {
            await using (var producerClient = new EventHubProducerClient(connectionString, eventHubName))
            {
                try
                {
                    // Create a batch of events
                    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))))
                        {
                            throw new Exception($"The message \"{message}\" is too large for the batch.");
                        }
                    }

                    // Send the batch to the Event Hub
                    await producerClient.SendAsync(eventBatch);
                    Console.WriteLine("Sent a batch of 5 messages.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error sending messages: {ex.Message}");
                }
            }
        }

        // Receives messages from the Event Hub
        static async Task ReceiveMessagesAsync()
        {
            // Read from the default consumer group ($Default)
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            await using (var consumerClient = new EventHubConsumerClient(connectionString, consumerGroup, eventHubName))
            {
                Console.WriteLine($"Listening for events in consumer group: {consumerGroup}");

                try
                {
                    // Start processing events from all partitions
                    await foreach (PartitionEvent partitionEvent in consumerClient.ReadEventsAsync())
                    {
                        string messageBody = Encoding.UTF8.GetString(partitionEvent.Data.EventBody.ToArray());
                        Console.WriteLine($"Received message: \"{messageBody}\" from partition {partitionEvent.Partition.Id}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error receiving messages: {ex.Message}");
                }
            }
        }
    }
}
            

4. Run the Application

Build and run your application from the terminal.

Using .NET (C#)

dotnet run

You should see output indicating that messages have been sent and received.

Next Steps