Dominic Pascasio
Posted on September 2, 2022
Warning! This code is for demonstration purposes only.
-
Create an empty ASP.NET web app:
dotnet new web -o TinyChat
-
In your
Program.cs
, addSignalR
service, set to serve static files and map theSignalR
hub.
var builder = WebApplication.CreateBuilder(args); builder.Services.AddSignalR(); var app = builder.Build(); app.UseStaticFiles(); app.MapHub<ChatHub>("/ChatHub"); app.Run();
-
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); } }
-
Add folder
wwwroot
in the project directory. Then addchat.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>
-
In
wwwroot
, addchat.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(); }); });
Run the app using
dotnet run
and go tohttps://localhost:<port>/chat.html
.
Resource
Microsoft Docs
💖 💪 🙅 🚩
Dominic Pascasio
Posted on September 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.