Free Web Development Online Tutorials, Learn to Code
How to send message to a group using SignalR Asp.net Core 3.1, SignalR group message example

SignalR Group Message Example in Asp.Net Core

In this signalr tutorial you will learn how to send message to a group.

If you are very new to signalR, I suggest you to go through earlier post about how to send message to all users, like live chat example using signalr.

Sending Message to a Group in SignalR

In this SignalR group message example you will learn how to broadcast messages to a particular group.

Like in earlier example, instead of sending message to all users, here we send message to only those users who has joined a particular group.

Framework: SignalR Core Asp.net Core 3.1 Example

How to send group message in SignalR Core

Open your visual studio and create asp.net core razor page project, You can choose MVC project also.

First, make sure you have installed all required packages from Nuget package manager. install Microsoft.AspNetCore.SignalR
Microsoft.AspNetCore.SignalR.Client
Microsoft.AspNetCore.SignalR.Core

Create Hub class with methods

Second, create a Hub class with any name you want, like in example below MessageHub, the class must inherit from Hub class.

then create three methods SendMessage, JoinGroup, SendMessageToGroup like example below.

signalr hub methods

using System;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Client;
using System.Threading.Tasks;
[HubName("MessageHub")]
public class MessageHub : Hub
{
    public Task JoinGroup(string group)
    {
      return Groups.AddToGroupAsync(Context.ConnectionId, group);
    }

   public async Task SendMessage(string sender, string message)
    {
        await Clients.All.SendAsync("SendMessage", sender, message);
    }  

   public Task SendMessageToGroup(string groupname, string sender, string message)
    {
     return Clients.Group(groupname).SendAsync("SendMessage", sender, message);
    }
}

Remember, we cannot have function overloading in hub function definition, so each function name needs to be unique, later I will explain this part with some example.

SignalR Startup file configuration

In startup.cs file you need to do following changes to register signalr middleware in http pipeline.

In ConfigureServices method, add the SignalR in service pipeline.

public void ConfigureServices(IServiceCollection services)
{
     services.AddSignalR();
}

Now configure the endpoint of newly created hub MessageHub class.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapHub<MessageHub>($"/{nameof(MessageHub)}");
            });
}

SignalR Client implementation

In razor view we create a simple form to post signalr message, this will be type of broadcasting to all users whoever accessing the same client.

In this demo, you will see how message getting broadcasted to only those users , who has joined the group by clicking “join group” button on the form.

signalr group message example

Note, here i have used session id as differentiator, to indentify each post with a unique id, in real-time scenario you probably can capture the username as differentiator.

Now I create a simple html form in razor page.

<div class="signalr-demo">

    <input type="button" value="Join Group" id="btnPrivateGroup" />

    <div id="senderUId">@HttpContext.Session.Id</div>
    <form id="messageform">            
        <input type="text" id="messagebox" />
        <input type="button" value="Send Message" id="btnSend" />
    </form>
    <hr />
    <ul id="messageList" style="text-align:left;"></ul>
</div>

Now, Add the signalR script reference in chtml file, this needs to be done before the form design part.

<script src="~/lib/signalr/signalr.js"></script>

Create signalR connection object instance in javascript code.

<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/MessageHub")
.build();
connection.start()
.catch(err => alert(err.toString()));
</script>

Now we invoke the signalr method "JoinGroup" with hardcoded parameter value "PrivateGroup" (this is for only example), In real life application scenario, you probably need to get the group name dynamically, and each group name needs to be unique.

$(document).ready(function () {
    $("#btnPrivateGroup").click(function (e) {        
        connection.invoke('JoinGroup', "PrivateGroup");
        e.preventDefault();
    });
});

Now we invoke the signalr method "SendMessage" with parameter values. and display the result on page.

When user click on send button, the message to be posted to server side using signalR connection hub.

<script>
$(document).ready(function () {
    $("#btnSend").click(function (e) {
        let message = $('#messagebox').val();
        let sender = $('#senderUId').text();
        $('#messagebox').val('');

        connection.invoke('SendMessageToGroup', group, sender, message);

        e.preventDefault();
    });
});


function appendLine(uid, message) {
        let nameElement = document.createElement('strong');
        nameElement.innerText = `${uid}:`;
        let msgElement = document.createElement('em');
        msgElement.innerText = ` ${message}`;
        let li = document.createElement('li');
        li.appendChild(nameElement);
        li.appendChild(msgElement);
        $('#messageList').append(li);
};
</script>

Thus whenever you post any message after clicking the join group button, the message will appear to all the clients who has joined the group.

Notice, the relation for each unique group is based on "ConnectionId + group name".

public Task JoinGroup(string group)
    {
        return Groups.AddToGroupAsync(Context.ConnectionId, group);
    }

to broadcast message to any particular group Clients.Group(groupname).SendAsync("SendMessage", sender, message).

public Task SendMessageToGroup(string groupname, string sender, string message)
    {
        return Clients.Group(groupname).SendAsync("SendMessage", sender, message);
    }

Hope you understood the implementation, and replicate in your real-time signalR application development.


 
Asp.net Core SignalR Example
ASP.NET MVC Interview Questions Answers

online courses
Asp.Net Core C# Examples | Join Asp.Net MVC Course