SignalR Hubs
Syntax
public class MyHub : Hub
{
public void SendMessage(string user, string message)
{
Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Example
public class ChatController : Controller
{
private readonly IHubContext<MyHub> _hubContext;
public ChatController(IHubContext<MyHub> hubContext)
{
_hubContext = hubContext;
}
public async Task<IActionResult> SendMessage(string user, string message)
{
await _hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
return Ok();
}
}
Explanation
SignalR Hubs provide a high-level messaging API for real-time communication between clients and servers. Hubs allow clients to call server-side methods, and vice versa, using a simple and intuitive syntax. At the core of Hubs is the concept of groups, which allow clients to be organized into logical groups based on any criteria. Hubs provide built-in support for managing connections, and can automatically scale to support large numbers of clients.
Use
SignalR Hubs are often used in real-time web applications where live updates are required, such as chat applications, real-time analytics, and multiplayer games. By using Hubs, developers can eliminate the need for manual low-level WebSocket programming, and focus on the core functionality of their application.
Important Points
- SignalR Hubs are a high-level messaging API for real-time communication
- Hubs provide a simple and intuitive syntax for calling server-side methods
- Hubs support the concept of groups for organizing clients
- Hubs provide built-in support for managing connections and scaling to large numbers of clients
Summary
SignalR Hubs provide a powerful API for real-time communication between clients and servers. With built-in support for managing connections and scaling to large numbers of clients, Hubs are an essential tool for developers building real-time web applications.