Peer-to-Peer Chat
You can configure the Telerik UI Chat component for ASP.NET Core and a ASP.NET Core SignalR service to create a Peer-to-Peer Chat application.
For the complete project, refer to the Chat Peer to Peer example.
To create the Peer-to-Peer Chat, you have to implement the SignalR Hub server and then to implement the application client:
- Create the new application
- Configure the SignalR Hub server
- Initialize the Chat
- Configure the SignalR client Hub proxy
Creating the New Application
Depending on your preferred editor, use any of the following approaches:
- Create a new Telerik UI for ASP.NET Core application from the Standard template
- Create a new .NET Core application in Visual Studio and include the Telerik UI for ASP.NET Core package
- Create a new .NET Core application with the CLI and include the Telerik UI for ASP.NET Core package
For .NET 6 and later versions, SignalR is included as part of the ASP.NET Core shared framework, so no additional package installation is required for the server-side SignalR functionality.
Configuring the SignalR Hub Server
-
Modify
Program.cs
to configure SignalR services and routing.C#using Microsoft.AspNetCore.SignalR; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); // Add the SignalR service. builder.Services.AddSignalR(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); // Map the SignalR Hub to the specified route. app.MapHub<ChatHub>("/chat"); app.Run();
-
Add a
ChatHub
class to the project.C#using Microsoft.AspNetCore.SignalR; namespace YourAppNamespace { // The Hub class should inherit from Microsoft.AspNetCore.SignalR.Hub public class ChatHub : Hub { public async Task Send(string senderId, string senderName, string message) { // Broadcast the message to all clients except the sender. await Clients.Others.SendAsync("broadcastMessage", senderId, senderName, message); } public async Task SendTyping(string senderId, string senderName) { // Broadcast the typing notification to all clients except the sender. await Clients.Others.SendAsync("typing", senderId, senderName); } } }
Initializing the Chat
Initialize the Chat and implement handlers for its SendMessage
and Input
events.
@{
var name = Guid.NewGuid().ToString();
}
@(Html.Kendo().Chat()
.Name("chat")
.AuthorId(@name)
.IsTypingField("isTyping")
.Events(events => events
.Input("onInput")
.SendMessage("onSendMessage")
)
)
Configuring the SignalR Client Hub Proxy
-
Add the SignalR JavaScript client library. You can use NPM to install the package or reference the library directly from CDN.
Using npm
bashnpm install @microsoft/signalr
Then copy the file from
node_modules/@microsoft/signalr/dist/browser/signalr.min.js
towwwroot/lib/signalr/
.Using CDN
Reference the library directly from CDN in the View.
HTML<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.0/signalr.min.js"></script>
-
Include the SignalR script on the View that contains the Chat declaration.
HTML<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.0/signalr.min.js"></script>
-
Initialize the SignalR Hub connection.
JS// Point to the Hub remote endpoint. window.chatHub = new signalR.HubConnectionBuilder() .withUrl('/chat') .build();
-
Start the Hub connection and configure it to handle errors.
JSchatHub.start() .then(function () { console.log('SignalR connection started.'); }) .catch(function(err) { console.error('Error starting SignalR connection: ' + err.toString()); });
-
Attach the event handlers for the respective remote Hub actions.
JS$(document).ready(function() { chatHub.on('broadcastMessage', function(senderId, senderName, message) { const chat = $("#chat").getKendoChat(); // Check for a "typing" message. let typingMessages = $.grep(chat.dataSource.data(), function(item){ return item.isTyping == true ? item.id : ""; }); if(typingMessages.length > 0) { if(typingMessages[0].id != null) { let messageObject = chat.dataSource.get(typingMessages[0].id); if (messageObject) { // Update the "typing" message with the received message text. let updatedMessage = chat.updateMessage(messageObject, { text: message, isTyping: false }); } } } else { // Post the received message in the Chat. chat.postMessage({ id: kendo.guid(), authorId: senderId, authorName: senderName, authorImageUrl:currentUser.iconUrl, text: message, isTyping: false }); } }); chatHub.on('typing', function(senderId, senderName) { console.log(senderName + ' is typing'); const chat = $("#chat").getKendoChat(); chat.postMessage({ id: kendo.guid(), isTyping: true, authorId: senderId, authorName: senderName, authorImageUrl: currentUser.iconUrl }); }); });
-
Start the Peer-to-Peer Chat application. To test the real-time messages, open the page with the Chat in two browser windows.