top of page

Azure SignalR Service: Revolutionize Real-time Communication

Updated: Oct 17, 2023

In an increasingly interconnected digital world, the demand for real-time communication and interaction has become paramount. Whether it's enabling live chats, multiplayer gaming, or collaborative applications, the ability to instantly exchange data between clients and servers is crucial. This is where Azure SignalR Service steps in, revolutionizing the way we build and scale real-time web applications.


Table of Contents:

Use cases

Features of Azure SignalR Service


What is Azure SignalR Service?

Azure SignalR Service is a fully managed service that enables real-time communication in web and mobile applications. It is designed to be used with a broad range of clients, including browsers, mobile devices, and servers.


Azure SignalR Service can handle large-scale client connections and provides a number of features that make it easy to build real-time applications, such as:

  • Support for multiple protocols, including WebSocket, HTTP, and SignalR

  • Automatic scaling to meet the needs of your application

  • Built-in security and reliability

  • Support for global distribution

Here are some of the benefits of using Azure SignalR Service:

  • Scalability: Azure SignalR Service can automatically scale to meet the needs of your application, so you don't have to worry about managing capacity.

  • Reliability: Azure SignalR Service is a highly reliable service that is backed by Microsoft's global infrastructure.

  • Security: Azure SignalR Service provides built-in security features that help to protect your applications from attack.

  • Global distribution: Azure SignalR Service is available in regions all over the world, so you can deploy your applications close to your users.

Use Cases

Azure SignalR Service caters to a wide range of use cases, making it an invaluable tool for developers across industries:

  1. Chat Applications: Create chat rooms, group chats, and private messaging with ease, as demonstrated in our example "Create a Chat Room using Azure SignalR Service."

  2. Live Dashboards: Build real-time dashboards that provide live updates and insights, ideal for monitoring systems, sales data, or sports scores.

  3. Gaming: Implement multiplayer games with low-latency communication, ensuring a seamless and immersive gaming experience.

  4. Collaborative Apps: Develop collaborative applications that enable real-time document editing, shared whiteboards, and co-authoring.

  5. Notifications: Send instant notifications to users about events, messages, or updates, ensuring they stay engaged and informed.

  6. IoT: Connect and communicate with IoT devices in real time, enabling remote control and monitoring.

Also Read:


Features of Azure SignalR Service:

Azure SignalR Service provides several features that make it an excellent choice for developers:

  1. Automatic Scale-out: Azure SignalR Service automatically scales out to handle increased load, ensuring that your application remains responsive even under heavy traffic.

  2. Integration with Azure Services: Azure SignalR Service can be integrated with other Azure services like Azure Functions, allowing you to run real-time messaging web apps in a serverless environment.

  3. Authentication and Authorization: Azure SignalR Service integrates with Azure Active Directory, allowing you to authenticate users and authorize access to your SignalR hubs.

  4. Real-time Metrics: Azure SignalR Service provides real-time metrics that help you monitor the performance of your application. You can track metrics like connection count, message count, and error count.

  5. Service Modes: Azure SignalR Service supports three service modes: Default, Serverless, and Classic. In Default mode, instead of connecting client and hub server directly, client and server both connect to SignalR Service and use the service as a proxy.


Now, let's dive deeper into the capabilities of Azure SignalR Service by exploring a practical example: "Create a Chat Room using Azure SignalR Service." This example will walk you through the process of building a real-time chat application using the Azure SignalR Resource, showcasing how easily it can be integrated into your projects for instant communication.


Example: Create a Chat Room using Azure SignalR Service

In this example, we'll demonstrate how to build a real-time chat room application using Azure SignalR Service. Azure SignalR provides the infrastructure for WebSocket-based communication, allowing users to exchange messages instantly. You'll create a user interface with HTML and JavaScript and connect it to the SignalR hub. Users can enter their names, send messages, and receive messages from others in the chat room. This example showcases the power of SignalR for building interactive and engaging web applications.


STEP 1: Create Azure SignalR Resource

Follow the below steps to create an Azure SignalR resource:

STEP 1: Go to the Azure marketplace. Search for "SignalR Service" and click on "Create".

Azure SignalR Service 1

STEP 2: Under the basic section, provide the following details:

  1. Subscription

  2. Resource group

  3. Resource Name

  4. Pricing tier

Azure SignalR Service 2

Click "Next: Networking".


STEP 3: Now, in the networking section, select the "Public endpoint" as the connectivity method.

Azure SignalR Service 3

STEP 4: There's no need to make any changes in the tags section. Click on "Review + create".

Azure SignalR Service 4


STEP 5: Review all the information you have entered till now.


STEP 6: Now, when you click Create, the deployment process will begin. You will see a progress image. See the below image.

Azure SignalR Service 5

STEP 6: After the deployment is completed, click on "Go to resource".


Azure SignalR Service 6

STEP 7: In the Settings section, click "keys". Copy the "Connection string".


Azure SignalR Service 7


STEP 2: Create ASP.NET Core Web App

Create a folder for your project where you have the appropriate permissions. For example, you can use the E:\Testing\chattest folder.


Here's how you can do it using the command prompt:


STEP 1: Open the terminal windows and navigate to the location where you want to create a new folder. If you want to use the suggested location and have an E: drive, you would use the following command:

cd E:\Testing

STEP 2: Create a new folder named chattest using the following command:

mkdir chattest

STEP 3: Navigate into your new folder:

cd chattest

STEP 4: Now you’re in your new project folder and can create the new ASP.NET Core web app project using the .NET Core CLI:

dotnet new web

This will create a new web application in your chattest folder.


The advantage of using the .NET Core CLI is that it’s available across Windows, macOS, and Linux platforms, allowing you to create .NET Core projects from any of these operating systems.


STEP 3: Add a Secret Manager to the Project

The Secret Manager tool stores sensitive data for development work outside your project tree. This approach helps prevent the accidental sharing of app secrets in source code.


In the folder, initialize UserSecretsId by running the following command:

dotnet user-secrets init

Add a Secret: Add a secret named Azure:SignalR:ConnectionString to Secret Manager. This secret will contain the connection string to access your SignalR Service resource. Azure:SignalR:ConnectionString is the default configuration key that SignalR looks for to establish a connection. Replace <Your connection string> in the following command with the connection string for your SignalR Service resource:

dotnet user-secrets set Azure:SignalR:ConnectionString "<Your connection string>"

Remember, you must run this command in the same directory as the csproj file.


Accessing Secrets:

This secret is accessed with the Configuration API. A colon (:) works in the configuration name with the Configuration API on all supported platforms.


STEP 4: Add Azure SignalR to Web App

Add a reference to the Microsoft.Azure.SignalR NuGet package by running the following command:

dotnet add package Microsoft.Azure.SignalR

Update Program.cs:

Open Program.cs and update the code to call the AddSignalR() and AddAzureSignalR() methods to use Azure SignalR Service:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR().AddAzureSignalR();
var app = builder.Build();

app.UseDefaultFiles();
app.UseRouting();
app.UseStaticFiles();
app.MapHub<ChatSampleHub>("/chat");
app.Run();

Add a Hub Class:

In SignalR, a hub is a core component that exposes a set of methods that can be called by the client. In your project directory, add a new folder named Hub. Add a new hub code file named ChatHub.cs to the new folder.


Define Your Hub Class:

Add the following code to ChatSampleHub.cs to define your hub class and save the file.

using Microsoft.AspNetCore.SignalR;

public class ChatSampleHub : Hub
{
    public Task BroadcastMessage(string name, string message) =>
        Clients.All.SendAsync("broadcastMessage", name, message);

    public Task Echo(string name, string message) =>
        Clients.Client(Context.ConnectionId)
                .SendAsync("echo", name, $"{message} (echo from server)");
}

Add Client Interface for Web App:

The client user interface for this chat room app will consist of HTML and JavaScript in a file named index.html in the wwwroot directory.


In the ASP.NET Core, the "wwwroot" directory is where you typically store static files like HTML, CSS, JavaScript, images, and other client-side assets. These files are publicly accessible to web clients, making them available for download by users' web browsers.

<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
    <title>Azure SignalR Group Chat</title>
</head>
<body>
    <h2 class="text-center" style="margin-top: 0; padding-top: 30px; padding-bottom: 30px;">Azure SignalR Group Chat</h2>
    <div class="container" style="height: calc(100% - 110px);">
        <div id="messages" style="background-color: whitesmoke; "></div>
        <div style="width: 100%; border-left-style: ridge; border-right-style: ridge;">
            <textarea id="message"
                      style="width: 100%; padding: 5px 10px; border-style: hidden;"
                      placeholder="Type message and press Enter to send..."></textarea>
        </div>
        <div style="overflow: auto; border-style: ridge; border-top-style: hidden;">
            <button class="btn-warning pull-right" id="echo">Echo</button>
            <button class="btn-success pull-right" id="sendmessage">Send</button>
        </div>
    </div>
    <div class="modal alert alert-danger fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <div>Connection Error...</div>
                    <div><strong style="font-size: 1.5em;">Hit Refresh/F5</strong> to rejoin. ;)</div>
                </div>
            </div>
        </div>
    </div>

    <!--Reference the SignalR library. -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js"></script>
    
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {

            const generateRandomName = () =>
                Math.random().toString(36).substring(2, 10);

            let username = generateRandomName();
            const promptMessage = 'Enter your name:';
            do {
                username = prompt(promptMessage, username);
                if (!username || username.startsWith('_') || username.indexOf('<') > -1 || username.indexOf('>') > -1) {
                    username = '';
                    promptMessage = 'Invalid input. Enter your name:';
                }
            } while (!username)

            const messageInput = document.getElementById('message');
            messageInput.focus();

            function createMessageEntry(encodedName, encodedMsg) {
                var entry = document.createElement('div');
                entry.classList.add("message-entry");
                if (encodedName === "_SYSTEM_") {
                    entry.innerHTML = encodedMsg;
                    entry.classList.add("text-center");
                    entry.classList.add("system-message");
                } else if (encodedName === "_BROADCAST_") {
                    entry.classList.add("text-center");
                    entry.innerHTML = `<div class="text-center broadcast-message">${encodedMsg}</div>`;
                } else if (encodedName === username) {
                    entry.innerHTML = `<div class="message-avatar pull-right">${encodedName}</div>` +
                        `<div class="message-content pull-right">${encodedMsg}<div>`;
                } else {
                    entry.innerHTML = `<div class="message-avatar pull-left">${encodedName}</div>` +
                        `<div class="message-content pull-left">${encodedMsg}<div>`;
                }
                return entry;
            }

            function bindConnectionMessage(connection) {
                var messageCallback = function (name, message) {
                    if (!message) return;
                    var encodedName = name;
                    var encodedMsg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                    var messageEntry = createMessageEntry(encodedName, encodedMsg);

                    var messageBox = document.getElementById('messages');
                    messageBox.appendChild(messageEntry);
                    messageBox.scrollTop = messageBox.scrollHeight;
                };
                connection.on('broadcastMessage', messageCallback);
                connection.on('echo', messageCallback);
                connection.onclose(onConnectionError);
            }

            function onConnected(connection) {
                console.log('connection started');
                connection.send('broadcastMessage', '_SYSTEM_', username + ' JOINED');
                document.getElementById('sendmessage').addEventListener('click', function (event) {
                    if (messageInput.value) {
                        connection.send('broadcastMessage', username, messageInput.value);
                    }

                    messageInput.value = '';
                    messageInput.focus();
                    event.preventDefault();
                });
                document.getElementById('message').addEventListener('keypress', function (event) {
                    if (event.keyCode === 13) {
                        event.preventDefault();
                        document.getElementById('sendmessage').click();
                        return false;
                    }
                });
                document.getElementById('echo').addEventListener('click', function (event) {
                    connection.send('echo', username, messageInput.value);

                    messageInput.value = '';
                    messageInput.focus();
                    event.preventDefault();
                });
            }

            function onConnectionError(error) {
                if (error && error.message) {
                    console.error(error.message);
                }
                var modal = document.getElementById('myModal');
                modal.classList.add('in');
                modal.style = 'display: block;';
            }

            const connection = new signalR.HubConnectionBuilder()
                .withUrl('/chat')
                .build();
            bindConnectionMessage(connection);
            connection.start()
                .then(() => onConnected(connection))
                .catch(error => console.error(error.message));
        });
    </script>
</body>
</html>

The above code focuses on building the front-end of a chat room application. It is a web-based interface that allows users to send and receive messages in real-time within a chat room. The key components of this code include:


The code performs several key functions to create a functional chat room application:

  1. User Name Generation: It generates a random username for the user and prompts the user to enter their name, ensuring it is not empty and does not contain certain characters.

  2. Message Display: It defines a function to create and display chat messages. Messages are styled differently based on whether they are system messages, broadcast messages, or user messages.

  3. Real-Time Communication: The code establishes a connection to the SignalR hub using the URL "/chat." It binds event handlers to send and receive messages in real-time. Users can send messages by pressing the "Send" button or by pressing Enter, and they can also request an "echo" of their message. Messages received are displayed in the chat interface in real-time.

  4. Connection Error Handling: If a connection error occurs, the code displays a modal dialog to alert the user and advises them to refresh the page to rejoin the chat.


STEP 5: Build and Run the App Locally

Run the following command to run the web app locally:

dotnet run

The app will be hosted locally with output containing the localhost URL, for example:

Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development

STEP 6: Test the App

Open two browser windows. In each browser, go to the localhost URL shown in the output window, for example, http://localhost:5000/. You’re prompted to enter your name. Enter a client name for both clients and test pushing message content between both clients by using the Send button.


That’s it! You’ve now created an ASP.NET Core web app using the .NET Core CLI, integrated it with Azure SignalR, and tested it locally. Remember that Secret Manager is used only for testing the web app while it’s hosted locally. After the web app is deployed to Azure, you’ll use an application setting instead of storing the connection string with Secret Manager.


Conclusion

Azure SignalR Service opens new horizons in real-time communication, making it accessible and scalable for developers across various domains. This managed service streamlines the process of building interactive applications, eliminating the complexities of infrastructure management and enabling the creation of dynamic, engaging user experiences.

bottom of page