Real-Time Dashboard using Azure SignalR Hub
Mohammed Shamseer Vettan
Software Development/Delivery Manager | Digital Transformation & Integration Specialist | Lead & Technology Specialist | Programmer
From the article by Mr. Darshana Mihiran Edirisinghe
In this article, we are going to discuss creating a real-time application using Azure SignalR, .NET API, and a React application. This is a great choice for building interactive, collaborative applications like chat, live dashboards, or online gaming.
This Article covers the below topics,
Introduction
When implementing real-time applications in a .NET API, SignalR is the primary and most well-established option. SignalR is a library provided by Microsoft specifically for building real-time features in .NET applications. However, there are other alternative options and technologies you can consider for real-time applications in .NET.
1. SignalR:
SignalR is a robust choice for adding real-time capabilities to your .NET Core API. It supports a range of communication protocols, including WebSockets, Server-Sent Events, and more. You can create hubs for managing real-time communication
2. WebSockets (System.Net.WebSockets):
You can directly use the System.Net.WebSockets library in .NET Core to implement WebSocket communication in your API. This is a lower-level approach compared to SignalR and provides fine-grained control over WebSocket connections.
3. gRPC with Real-Time Support:
gRPC, which is a high-performance remote procedure call framework, can be extended to support real-time features using bidirectional streaming. You can implement real-time features in your .NET Core API by utilizing gRPC’s bidirectional communication capabilities.
4. Custom Protocols with ASP.NET Core:
You can create custom real-time protocols in your ASP.NET Core application, handling WebSocket or other communication methods directly. This approach provides maximum flexibility but requires significant development effort.
5. Third-Party Libraries:
There are third-party libraries available for real-time communication in .NET Core, although they may not be as feature-rich or widely adopted as SignalR. Some examples include Fleck (a WebSocket library) and WampSharp (an implementation of the Web Application Messaging Protocol).
6. RabbitMQ or Other Message Brokers:
If your real-time application involves messaging or event-driven scenarios, you can use a message broker like RabbitMQ in combination with your .NET Core API to implement real-time messaging.
Create Azure SignalR Service
Creating an Azure SignalR Service involves several steps.
Security and Authentication
Implement any required security and authentication mechanisms for your application. Azure SignalR Service can work with Azure Active Directory (Azure AD) for authentication if needed.
Scale and Optimize
Configure scaling options if your application is expected to have varying workloads. Log in to the Azure Portal (https://portal.azure.com) with your Azure account. Navigate to the Azure SignalR Service that you’ve created by clicking on it in the Azure Portal.
Scale Up or Out
Azure SignalR Service can be scaled either vertically (scaling up) or horizontally (scaling out). Choose the scaling method based on your requirements.
Vertical Scaling (Scale Up): To scale up, increase the capacity of your service by changing the pricing tier. This increases the available resources for your SignalR service. In the Azure Portal, go to your SignalR service and click on “Scale-up.”
Horizontal Scaling (Scale Out): To scale out, add more instances of your SignalR service. This helps distribute the load across multiple instances. In the Azure Portal, go to your SignalR service and click on “Scale-out.” Specify the number of units you want to run in parallel.
Set Auto-Scale Rules (Optional): You can configure auto-scaling rules to automatically adjust the number of units based on usage metrics. This ensures your service is always right-sized and can handle fluctuations in traffic. In the Azure Portal, navigate to your SignalR service and click on “Auto-scale.” Create rules based on metrics like the number of connections or messages per second. Define the minimum and maximum number of units for auto-scaling.
Optimize Hub and Connection Management
Depending on your application’s needs, you can fine-tune how hubs and connections are managed. Configure hub methods for load distribution and optimization. Implement connection management
Set up monitoring and diagnostics for your Azure SignalR Service to track its performance and troubleshoot issues. Navigate to the Azure SignalR Service that you’ve created by clicking on it in the Azure Portal. Azure SignalR Service provides diagnostic logs that capture information about service activities and usage. In the Azure Portal, go to your SignalR service. Under “Settings,” select “Diagnostic settings.” Click on “Add diagnostic setting.” Provide a name for the diagnostic setting. Under “Category details,” select the diagnostic categories you want to monitor, such as “Service and performance counters” or “Connectivity.” Choose a destination for the diagnostic logs, typically Azure Monitor, and configure the settings accordingly. Save the diagnostic setting.
领英推荐
Configure Metrics Collection
Metrics are essential for understanding the performance and usage of your SignalR service. Azure SignalR Service provides metrics like connections, messages sent, and messages received. In the Azure Portal, go to your SignalR service. Under “Monitoring,” select “Metrics.” Choose the metrics you want to collect and visualize. Set up alerts if necessary to be notified of critical issues.
Set Up Alerts
Alerts help you proactively respond to issues or unusual events in your SignalR service. You can create alerts based on metric thresholds, diagnostic logs, or other conditions. In the Azure Portal, go to your SignalR service. Under “Monitoring,” select “Alerts.” Click on “New alert rule” to create a new alert rule. Configure the alert criteria, such as metric thresholds, conditions, and alert actions (e.g., sending an email or triggering an Azure Function). Save the alert rule.
Integrate with Application Insights
Application Insights is a powerful tool for monitoring the performance of your application, including interactions with the SignalR service. In the Azure Portal, go to your SignalR service. Under “Settings,” select “Application Insights.” You can choose to link an existing Application Insights resource or create a new one. Follow the steps to link the Application Insights resource to your SignalR service.
Implement Azure SingalR in .NET API
dotnet add package Microsoft.Azure.SignalR
3. Create a SignalR Hub. Create a SignalR hub class by adding a new class to your project. The hub class should derive from Hub .
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRApp.Hubs
{
public class RealTimeHub : Hub
{
public async Task SendMessage(string user, string message)
{
// Broadcast the message to all connected clients
await Clients.All.SendAsync("Hi", user, message);
}
}
}
4. In your Program.cs, you should configure the Azure SignalR Service connection string using the IConfiguration interface, which retrieves the connection string from your appsettings.json or other configuration sources.
services.AddSignalR().AddAzureSignalR(Configuration.GetConnectionString("AzureSignalR"));
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/RealTimeHub"); // Map the ChatHub to a specific endpoint
});
5. Create API Endpoint.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using MyAzureSignalRApp.Hubs;
namespace AzureSignalRApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DashboardController : ControllerBase
{
private readonly IHubContext<ChatHub> _hubContext;
public DashboardController(IHubContext<ChatHub> hubContext)
{
_hubContext = hubContext;
}
[HttpGet]
public async Task<IActionResult> SendMessage(string message)
{
await _hubContext.Clients.All.SendAsync("ReceiveMessage", message);
return Ok();
}
}
}
Hub methods are typically called from client applications (e.g., web browsers, mobile apps) to send real-time messages to the server and, in turn, to other connected clients. However, in some cases, you may need to invoke hub methods from your server-side code, such as from a controller in a .NET Core API.
Implement Azure SingalR in React Application
Create a React application. install the SignalR client library. You can do this using npm or yarn:
npm install @microsoft/signalr
# or
yarn add @microsoft/signalr
Create a SignalR Service Module.
// signalRService.js
import { HubConnectionBuilder } from '@microsoft/signalr';
const signalRService = {
connection: null,
startConnection: (hubUrl) => {
signalRService.connection = new HubConnectionBuilder()
.withUrl(hubUrl)
.build();
signalRService.connection.start().then(() => {
console.log('SignalR connection established.');
}).catch((err) => {
console.error('Error starting SignalR connection:', err);
});
},
onReceiveMessage: (callback) => {
signalRService.connection.on('ReceiveMessage', (user, message) => {
callback(user, message);
});
},
sendMessage: (user, message) => {
signalRService.connection.invoke('SendMessage', user, message)
.catch((err) => {
console.error('Error sending message:', err);
});
},
};
export default signalRService;
Use SignalR in React Components.
import React, { useEffect, useState } from 'react';
import signalRService from './signalRService';
function App() {
const [messages, setMessages] = useState([]);
const [user, setUser] = useState('');
const [message, setMessage] = useState('');
useEffect(() => {
signalRService.startConnection('/RealTimeHub');
signalRService.onReceiveMessage((receivedUser, receivedMessage) => {
setMessages([...messages, { user: receivedUser, message: receivedMessage }]);
});
return () => {
signalRService.connection.stop();
};
}, [messages]);
const sendMessage = () => {
signalRService.sendMessage(user, message);
setMessage('');
};
return (
<div className="App">
<h1>React SignalR Chat</h1>
<div>
<input
type="text"
placeholder="Your Name"
value={user}
onChange={(e) => setUser(e.target.value)}
/>
<input
type="text"
placeholder="Message"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
</div>
<div>
{messages.map((msg, index) => (
<div key={index}>
<strong>{msg.user}:</strong> {msg.message}
</div>
))}
</div>
</div>
);
}
export default App;
Best Practices
2. Organize your SignalR hub classes in a structured manner, keeping related hub methods and functionality together. This makes your code easier to understand and maintain.
3. Use Authorization and Authentication:
4. Validate input data in your hub methods to ensure it’s safe and that your server is protected from malicious input.
5. Error Handling.
6. Load Testing.
7. Logging and Diagnostics.
8. Real-Time Monitoring.
9. Message Size Considerations.