New to Telerik UI for ASP.NET CoreStart a free 30-day trial

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:

  1. Create the new application
  2. Configure the SignalR Hub server
  3. Initialize the Chat
  4. Configure the SignalR client Hub proxy

Creating the New Application

Depending on your preferred editor, use any of the following approaches:

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

  1. 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();
  2. 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.

Razor
    @{
        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

  1. Add the SignalR JavaScript client library. You can use NPM to install the package or reference the library directly from CDN.

    Using npm

    bash
    npm install @microsoft/signalr

    Then copy the file from node_modules/@microsoft/signalr/dist/browser/signalr.min.js to wwwroot/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>
  2. 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>
  3. Initialize the SignalR Hub connection.

    JS
    // Point to the Hub remote endpoint.
    window.chatHub = new signalR.HubConnectionBuilder()
        .withUrl('/chat')
        .build();
  4. Start the Hub connection and configure it to handle errors.

    JS
    chatHub.start()
        .then(function () {
            console.log('SignalR connection started.');
        })
        .catch(function(err) {
            console.error('Error starting SignalR connection: ' + err.toString());
        });
  5. 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
            });
        });
    });
  6. Start the Peer-to-Peer Chat application. To test the real-time messages, open the page with the Chat in two browser windows.

See Also