Client and Server Communication - SignalR Hubs
Syntax
Server-side
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
[HubName("myHub")]
public class MyHub : Hub
{
public void Send(string message)
{
Clients.All.broadcastMessage(message);
}
}
Client-side
var myHub = $.connection.myHub;
myHub.client.broadcastMessage = function (message) {
console.log(message);
};
$.connection.hub.start().done(function () {
myHub.server.send("Hello World!");
});
Example
Server-side
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
[HubName("chatHub")]
public class ChatHub : Hub
{
public void Send(string message)
{
Clients.All.broadcastMessage(message);
}
}
Client-side
var chatHub = $.connection.chatHub;
chatHub.client.broadcastMessage = function (name, message) {
console.log(name + ' says ' + message);
};
$.connection.hub.start().done(function () {
chatHub.server.send('John', 'Hello World!');
});
Output
John says Hello World!
Explanation
SignalR Hubs is a high-level library that helps you to write code for broadcasting messages to multiple clients simultaneously. Hubs are a higher-level abstraction built on top of the SignalR Persistent Connection API. Hubs are a great way to handle real-time communication scenarios like chat rooms, games, or stock tickers.
Use
SignalR Hubs is widely used to establish real-time bidirectional client-server communication over websockets or other supported transports. It is used in various scenarios like online chat applications, real-time scoreboards, or notifications.
Important Points
- In SignalR, a hub is a C# class that serves as a high-level pipeline that allows clients and servers to call methods on each other seamlessly.
- SignalR automatically generates a JavaScript proxy that allows clients to call server-side hub methods.
- Hub methods can be called from JavaScript on the client or from C# on the server.
- Hub methods can be invoked by all clients connected to the server, or a specific set of clients if you use groups.
- SignalR supports multiple transports, including WebSockets, Server-Sent Events (SSE), and long-polling.
Summary
SignalR Hubs is a high-level library that allows you to write real-time communication code for broadcasting messages to multiple clients simultaneously. It abstracts the WebSocket, Server-Sent Events (SSE), and long-polling transports into a single API that enables bidirectional communication between server and client. With the built-in hub pipeline, it is easy to broadcast messages to any connected clients. The easy-to-use abstraction model makes it an ideal choice for building real-time communication scenarios.