Simple .NET chat application with Azure Service Bus

Introduction

In this blog post, we will explore how to create a real-time chat service using Azure Service Bus. Azure Service Bus is a fully managed messaging service that enables communication between different components of your applications. We will build a simple chat application using Service Bus topics and subscribers, allowing users to send and receive messages in real-time.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • An Azure account with sufficient permissions to create resources.
  • Azure Service Bus namespace and connection string.

Azure Service Bus Topic

An Azure Service Bus Topic is a logical container for messages. It acts as a central hub where messages are sent by the sender and then forwarded to all associated subscriptions. Think of a topic as a message distribution channel that decouples message publishers from subscribers. Messages sent to a topic can be received by multiple subscribers concurrently.

In our chat application, we created a Service Bus topic named “chat,” where messages are published by chat clients and delivered to all subscribers (chat users). Topics are versatile and can be used in various scenarios, such as broadcasting events, distributing notifications, and implementing publish-subscribe patterns.

Azure Service Bus Subscription

A Subscription is a virtual representation of a message queue that receives messages from a specific topic. Subscriptions are associated with a topic and receive copies of the messages sent to that topic. Each subscription can have its own message filters, allowing you to control which messages it receives based on specific criteria.

In our chat application, we created a Service Bus subscription named “chat-user,” representing individual chat users. When chat clients send messages to the “chat” topic, the messages are forwarded to the “chat-user” subscription, and each user receives their copy of the message. Subscriptions enable selective message consumption and allow different groups of users to receive specific sets of messages.

Step 1: Create Azure Service Bus Topic

  1. Log in to the Azure portal and navigate to your Service Bus namespace.
  2. Click on “Topics” in the left menu and then click “Create” to create a new topic.
  3. Provide a unique name for the topic, such as “chat.”
  4. Configure other settings like “Default Message Time To Live” and “Duplicate Detection” as per your requirements.
  5. Click “Create” to create the topic.

Step 2: Create Subscribers

  1. Click on “Subscriptions” under the “chat” topic in the Azure portal.
  2. Click “Add” to create a new subscription.
  3. Provide a unique name for the subscription, such as “chat-user.”
  4. Optionally, configure the “Filter” and “Time To Live” settings if you want to filter or set a time-to-live for messages.
  5. Click “Create” to create the subscription.

Step 3: Implementing the Chat Service

Now, let’s dive into the code and implement our chat service using C# and Azure Service Bus.

class Chat
{
	private readonly ServiceBusClient client;
	private readonly ServiceBusSender sender;
	private readonly ServiceBusProcessor processor;

	public Chat(string serviceBusConnectionString, string topicName, string subscriptionName)
	{
		client = new ServiceBusClient(serviceBusConnectionString);
		sender = client.CreateSender(topicName);
		processor = client.CreateProcessor(topicName, subscriptionName, new ServiceBusProcessorOptions());
	}

	public async Task StartAsync()
	{
		// Start the processor to receive messages
		processor.ProcessMessageAsync += MessageHandler;
		processor.ProcessErrorAsync += ErrorHandler;
		await processor.StartProcessingAsync();

		Console.WriteLine("Chat started. Type your messages and press Enter to send. Type 'exit' to quit.");

		// Start the message sending loop
		while (true)
		{
			string message = Console.ReadLine();

			if (message.Equals("exit", StringComparison.OrdinalIgnoreCase))
			{
				break;
			}

			await SendMessageAsync(message);
		}

		// Stop the processor and close the client when done
		await processor.StopProcessingAsync();
		await client.DisposeAsync();
	}

	private async Task SendMessageAsync(string messageText)
	{
		using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

		try
		{
			var message = Encoding.UTF8.GetBytes(messageText);
			if (!messageBatch.TryAddMessage(new ServiceBusMessage(message)))
			{
				throw new Exception($"The message {message} is too large to fit in the batch.");
			}

			await sender.SendMessagesAsync(messageBatch);
			Console.WriteLine($"Sent: {messageText}");

			Console.ReadLine();
		}
		catch (Exception ex)
		{
			Console.WriteLine($"Error: {ex.Message}");
		}
	}

	private async Task MessageHandler(ProcessMessageEventArgs args)
	{
		string body = args.Message.Body.ToString();
		Console.WriteLine($"Received: {body} from subscription: {args.EntityPath}");

		await args.CompleteMessageAsync(args.Message);
	}

	private Task ErrorHandler(ProcessErrorEventArgs args)
	{
		Console.WriteLine(args.Exception.ToString());
		return Task.CompletedTask;
	}
}

class Program
{

	static async Task Main()
	{
		const string ServiceBusConnectionString= "YOUR CONNECTION STRING";
		string topicName = "chat";
		string subscriptionName = "chat-user";

		var chat = new Chat(ServiceBusConnectionString, topicName, subscriptionName);
		await chat.StartAsync();
	}
}

Step 4: Sending and Receiving Messages

In the Chat class, we have methods to send and receive messages using the Azure Service Bus SDK. The StartAsync method initiates the message processor to receive messages in real-time.

Step 5: Running the Chat Application

  1. Replace ServiceBusConnectionString with your actual Azure Service Bus connection string in the Program class.
  2. Compile and run the application.
  3. The chat service will start processing messages from the specified topic and subscription.
  4. Type your messages and press “Enter” to send. Type “exit” to quit the chat.

Conclusion

Congratulations! You have successfully built a real-time chat service using Azure Service Bus topics and subscribers. Azure Service Bus provides a robust and scalable messaging platform for building various real-time communication applications.

Here’s a diagram depicting the architecture of our chat application using Azure Service Bus:

Sends Messages
Forwards Messages
Receives Messages
Chat Client
Azure Service Bus Topic 'chat'
Azure Service Bus Subscription 'chat-user'

In this diagram, the chat client sends messages to the Azure Service Bus topic ‘chat,’ which forwards those messages to the subscription ‘chat-user.’ The chat client receives messages from the subscription, enabling real-time communication between users.

Feel free to customize and expand this chat service as per your application’s requirements. Happy coding!

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم