Section 1 of 6

SignalR

🎯 What You'll Learn

  • What is SignalR
  • Creating a Hub
  • Sending messages
  • JavaScript client
  • Groups

What is SignalR?

SignalR enables real-time, bi-directional communication between server and clients using WebSockets, Server-Sent Events, or Long Polling.

Setup

Program.cs C#
builder.Services.AddSignalR();

var app = builder.Build();

app.MapHub<ChatHub>("/chatHub");

Creating a Hub

ChatHub.cs C#
using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

JavaScript Client

Install Package Bash
npm install @microsoft/signalr
chat.js JavaScript
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .build();

// Receive messages
connection.on("ReceiveMessage", (user, message) => {
    console.log(`${user}: ${message}`);
});

// Start connection
connection.start().catch(err => console.error(err));

// Send message
connection.invoke("SendMessage", user, message);

Sending to Specific Clients

Targeting Clients C#
// All clients
await Clients.All.SendAsync("ReceiveMessage", user, message);

// Caller only
await Clients.Caller.SendAsync("ReceiveMessage", user, message);

// All except caller
await Clients.Others.SendAsync("ReceiveMessage", user, message);

// Specific client
await Clients.Client(connectionId).SendAsync("ReceiveMessage", user, message);

Groups

Managing Groups C#
public async Task JoinGroup(string groupName)
{
    await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}

public async Task LeaveGroup(string groupName)
{
    await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
}

public async Task SendToGroup(string groupName, string message)
{
    await Clients.Group(groupName).SendAsync("ReceiveMessage", message);
}

InvenTrack Example

StockHub.cs C#
public class StockHub : Hub
{
    public async Task NotifyStockUpdate(int productId, int quantity)
    {
        await Clients.All.SendAsync("StockUpdated", productId, quantity);
    }
}
ProductsController.cs C#
public class ProductsController : Controller
{
    private readonly IHubContext<StockHub> _hubContext;

    [HttpPost]
    public async Task<IActionResult> UpdateStock(int id, int quantity)
    {
        // Update database...
        
        // Notify all clients
        await _hubContext.Clients.All.SendAsync("StockUpdated", id, quantity);
        
        return Ok();
    }
}

Key Takeaways

  • SignalR: Real-time communication
  • Hub: Server-side class for SignalR
  • Clients.All: Send to all connected clients
  • Clients.Caller: Send to calling client
  • Groups: Organize clients into groups
  • IHubContext: Send from outside Hub