signalr
  1. signalr-creating-hubs

Creating Hubs - SignalR

Introduction

SignalR is a real-time communication library, which enables server-side code to push content to connected clients instantly. SignalR supports WebSocket transport, which allows both server and client to send and receive messages from each other in real-time.

Syntax

To create a hub, you need to follow the following syntax:

public class YourHubName : Hub
{
    // Method to send messages to clients
    public void SendMessage(string user, string message)
    {
        Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Example

Let's have a look at the following example to demonstrate how to create a Hub using SignalR:

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

namespace SignalRHub.Hubs
{
    public class ChatHub : Hub
    {
        // Method to send messages to clients
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

Output

The SendMessage() method inside the ChatHub class will send a message to all the connected clients. The name of the message event is set to ReceiveMessage. The user and message parameters will be passed to the ReceiveMessage event to broadcast the sent message to all connected clients.

Explanation

When a message is sent using SignalR, it travels across a web socket, and thus eliminates the need to refresh the page to display the messages. The code for sending the message is contained in the hub, which is simple to execute using JavaScript.

To call the SendMessage() method from the client-side, we need to create a SignalR connection and then call the SendMessage() method using the created connection.

Use

You can use SignalR to build real-time functionality into your web applications, for example, chat applications, real-time notifications, and financial applications.

SignalR is an efficient way to push updates to the user's browser without an additional effort of poll requests.

Important Points

  • SignalR supports different transport protocols such as Web Sockets and Server-Sent Events.

  • A Hub is a high-level class that enables the server-side code to call methods on client-side Javascript code.

  • A Hub class is derived from the Microsoft.AspNetCore.SignalR.Hub class.

  • Hub Methods are broadcasted to multiple connected clients at the same time.

Summary

SignalR is a powerful library that provides real-time functionality for web applications. In this article, we discussed how to create a Hub in SignalR using C# and how to send messages to all connected clients using the SendMessage() method.

SignalR is a powerful tool to develop real-time applications, and it's effortless and efficient to use.

Published on: