Skip to content

JM89/test-signalr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Test project for Signal R integration

References Tutorial: Get started with ASP.NET Core SignalR

Basic Setup

  1. Create .NET Core 2.2 Web Application
  2. Add Microsoft.AspNetCore.App nuget package
  3. Add signalr.js libraries (LibMan) and include the scripts to the index page
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
  1. Create chat.js file into the js folder

  2. Create a background service for sending regularly messages to the UI

public class BackgroundMessageSender : BackgroundService
{
    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                // Sending msgs
                Thread.Sleep(5000);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
  1. Add background service to startup.cs
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        //services.Configure...
        services.AddHostedService<BackgroundMessageSender>();
    }
}

Listening messages sent by server from the UI

Server setup

  1. Create a Hub class with no content
public class NotificationHub : Hub
{

}
  1. Setup the Startup.cs for signal R
public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddSignalR();
    services.AddHostedService<BackgroundMessageSender>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseSignalR(routes =>
    {
        routes.MapHub<NotificationHub>("/notificationHub"); // define an explicit route for the UI client
    });
}
  1. Send messages from background service
 public class BackgroundMessageSender : BackgroundService
    {
        private IHubContext<NotificationHub> _hubCtx;

        public BackgroundMessageSender(IHubContext<NotificationHub> hubCtx)
        {
            _hubCtx = hubCtx;
        }

        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    // Send directly a message to a different channel
                    await _hubCtx.Clients.All.SendAsync("ReceivedMessageFromServer", "ServerToClient: Message for all");

                    Thread.Sleep(5000);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }

UI client setup

Add this code to chat.js:

var notificationHub = new signalR.HubConnectionBuilder().withUrl("/notificationHub").build();

notificationHub.start();
notificationHub.on("ReceivedMessageFromServer", function (data) {
    console.log(data);
});

Sending messages from UI to the server

Requirements

  • Hub class is created and startup.cs is setup

UI Client setup

  1. Add a button in index.cshtml
<input type="button" id="triggerAction" value="Trigger actions into the server" />
  1. Add this code to chat.js:
var notificationHub = new signalR.HubConnectionBuilder().withUrl("/notificationHub").build();
notificationHub.start();

document.getElementById("triggerAction").addEventListener("click", function (event) {
    notificationHub.invoke("TriggerAction", "exec").catch(function (err) {
        return console.error(err.toString());
    });
});

Server setup

public class NotificationHub : Hub
{
  public Task TriggerAction(string cmd)
  {
    Console.WriteLine("Command Received" + cmd);
    return Task.CompletedTask;
  }
}

Inside this method, you can do whatever you want such as:

  • broadcast more messages for more other UI clients
await Clients.All.SendAsync("ReceiveMessage", msg)
  • join a specific message group
await Groups.AddToGroupAsync(Context.ConnectionId, groupname)

About

Test project for Signal R integration

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published