Author : HASSAN MD TAREQ

What is Hub?

  • A hub is a server-side class that sends messages to and receives messages from clients by utilizing RPC
  • Server-side component written in C#, define callable actions, broadcast real-time events
  • SignalR uses hubs to communicate between clients and servers
  • SignalR Hubs API enables you to call methods on connected clients from the server. In the server code, you define methods that are called by client. In the client code, you define methods that are called from the server
  • A hub is a high-level pipeline that allows a client and server to call methods on each other
  • SignalR handles the dispatching across machine boundaries automatically, allowing clients to call methods on the server and vice versa
  • You can pass strongly-typed parameters to methods, which enables model binding
  • SignalR provides two built-in hub protocols: a text protocol based on JSON and a binary protocol based on MessagePack. MessagePack generally creates smaller messages compared to JSON
  • Hubs call client-side code by sending messages that contain the name and parameters of the client-side method. Objects sent as method parameters are deserialized using the configured protocol. The client tries to match the name to a method in the client-side code. When the client finds a match, it calls the method and passes to it the deserialized parameter data
  • Links:

Creating hub

Hubs/ChatHub.cs

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

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

Hub class

Hub class properties

Hub connection events

Hubs/ChatHub.cs

public class ChatHub : Hub
{
	public override async Task OnConnectedAsync()
	{

		// ... ... ...
		
		await Clients.Caller.SendAsync("ReceiveMessage", "Start Message", DateTimeOffset.UtcNow);
		
		// ... ... ...
		
		await base.OnConnectedAsync();
	}

	public override async Task OnDisconnectedAsync(Exception exception)
	{
		// ... ... ...
		
		await base.OnDisconnectedAsync(exception);
	}
}

Dependency injection

Any service can be injected into hub by contructor inject in the same way of Controller or PageModel

Hubs/ChatHub.cs

public class ChatHub : Hub
{
	private IFoo _foo;

	public ChatHub(IFoo foo){
		_foo = foo
	}
	
	public async Task SendMessage(string user, string message)
	{
		await Clients.All.SendAsync("ReceiveMessage", user, message);
	}
}

Injecting hub into controller

[Route("[controller]")]
public class ChatController : Controller
{
	private readonly IHubContext<ChatHub> _chatHub;

	public ChatController(IHubContext<ChatHub> chatHub)
	{
		_chatHub = chatHub;
	}

	// ... ... ...
}