DEV Community

Dominic Pascasio
Dominic Pascasio

Posted on • Edited on

1 1

ASP.NET Core - Tiny Chat App using SignalR

Warning! This code is for demonstration purposes only.

  1. Create an empty ASP.NET web app:

    dotnet new web -o TinyChat
    
  2. In your Program.cs, add SignalR service, set to serve static files and map the SignalR hub.

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSignalR();
    var app = builder.Build();
    
    app.UseStaticFiles();
    app.MapHub<ChatHub>("/ChatHub");
    app.Run();
    
  3. In your project directory, add ChatHub.cs that contains:

    using Microsoft.AspNetCore.SignalR;
    
    public class ChatHub : Hub
    {
        // this can be invoked from the client -- web browser in our example
        public async Task SendMessage(string username, string message)
        {
            // invoke ReceiveMessage on all clients connected
            await Clients.All.SendAsync("ReceiveMessage", username, message);
        }
    }
    
  4. Add folder wwwroot in the project directory. Then add chat.html which contains:

    <!DOCTYPE html>
    <html>
        <head></head>
        <body>
            <input id='usernameInput' placeholder='username' />
            <input id='messageInput' placeholder='message' />
            <button id='sendButton'>Send</button>
            <ul id='conversationList'></ul>
            <script src='https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.8/signalr.min.js'></script>
            <script src='/chat.js'></script>
        </body>
    </html>
    
  5. In wwwroot, add chat.js which contains:

    "use strict";
    document.addEventListener('DOMContentLoaded', function() {
    var connection = new signalR.HubConnectionBuilder().withUrl("/ChatHub").build();
    
    // Handler for receiving a message. This will be invoked by the server.
    connection.on("ReceiveMessage", function (username, message) {
        var messageItem = document.createElement("li");
        messageItem.textContent = `${username}: ${message}`; 
    
        var conversationList = document.querySelector("#conversationList");
        conversationList.prepend(messageItem);
    });
    
    // Initiate connection and set callback for error.
    connection.start().then(function () {
    
    }).catch(function (err) {
        return console.error(err.toString());
    });
    
    // Handler for sending message to the server.
    document.querySelector("#sendButton").addEventListener("click", function (event) {
        var username = document.querySelector("#usernameInput").value;
        var message = document.querySelector("#messageInput").value;
    
        connection.invoke("SendMessage", username, message)
        .catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    });
    
  6. Run the app using dotnet run and go to https://localhost:<port>/chat.html.

Resource
Microsoft Docs

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️