SignalR: Create Simple Chat Application

Posted on Updated on

In this tutorial we will learn basics of building a real-time app using SignalR. You learn how to:

  • Create a web project.
  • Add the SignalR client library.
  • Create a SignalR hub.
  • Configure the project to use SignalR.
  • Add code that sends messages from any client to all connected clients.

At the end, you’ll have a working chat application ready for fun!

Create a ASP.net core Web Application Project (Razor Pages)

New Project dialog in Visual Studio

Add a client side library:

By right clicking Project in Visual Studio add: @microsoft/signalr@latest by selecting unpkg the Provider.

Add Client-Side Library dialog - select library
  • Install SignalR.js and SignalR.min.js in wwwroot/js/signalr

Create: ChatHub.cs

Create a SignalR Hub by creating Hubs folder inside project and creating ChatHub.cs file inherited by Hub class placed in Microsoft.AspNetCore.SignalR

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

Update: Startup.cs file

//Add this in Using portion
using SignalRChat.Hubs;

//Add this line in ConfigureServices
services.AddSignalR();

//Add this line in EndPoint configuration
endpoints.MapHub<ChatHub>("/chatHub");

Update: Index.razor

<div class="container">
    <div class="row">&nbsp;</div>
    <div class="row">
        <div class="col-2">User</div>
        <div class="col-4"><input type="text" id="userInput" /></div>
    </div>
    <div class="row">
        <div class="col-2">Message</div>
        <div class="col-4"><input type="text" id="messageInput" /></div>
    </div>
    <div class="row">&nbsp;</div>
    <div class="row">
        <div class="col-6">
            <input type="button" id="sendButton" value="Send Message" />
        </div>
    </div>
</div>
<div class="row">
    <div class="col-12">
        <hr />
    </div>
</div>
<div class="row">
    <div class="col-12">
        <ul id="messagesList"></ul>
    </div>
</div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

Create: wwwroot/js/chat.js

"use strict";

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

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message, time) {
    var msg = message.replace(/&/g, "&amp;").replace(//g, "&gt;");
    var encodedMsg = " [ " + time + "] " + user + ": " + msg  ;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

Press CTRL+F5 to run the app without debugging.

  • Copy the URL from the address bar, open another browser instance or tab, and paste the URL in the address bar.
  • Choose either browser, enter a name and message, and select the Send Message button.The name and message are displayed on both pages instantly.

Buy Me A Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *