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

Peer-to-Peer Chat

You can configure the Telerik UI Chat component for ASP.NET MVC and a SignalR 2 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:

Configuring the SignalR Hub Server

  1. Add the Microsoft.AspNet.SignalR NuGet package to the application.

    Razor
     Install-Package Microsoft.AspNet.SignalR
  2. Create a Startup.cs file to configure the hub connection.

    Razor
     using Microsoft.Owin;
     using Owin;
    
     namespace YourAppNamespace
     {
         public class Startup
         {
             public void Configuration(IAppBuilder app)
             {
                 // Map the SignalR service
                 app.MapSignalR();
             }
         }
     }
  3. Create a Hubs folder and create a ChatHub class in it.

    Razor
     using Microsoft.AspNet.SignalR;
    
     namespace YourAppNamespace.Hubs
     {
         // The Hub class has to inherit from the Microsoft.AspNet.SignalR.Hub.
         public class ChatHub : Hub
         {
             public void Send(string senderId, string senderName, string message)
             {
                 // Broadcast the message to all clients except the sender.
                 Clients.Others.broadcastMessage(senderId, senderName, message);
             }
             
             public void SendTyping(string senderId, string senderName)
             {
                 // Broadcast the typing notification to all clients except the sender.
                 Clients.Others.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. Include the SignalR 2 script in the page. You can install Microsoft.AspNet.SignalR.JS NuGet package or reference the library directly from CDN.

    Using
    Install-Package Microsoft.AspNet.SignalR.JS

    Then reference the library in the View:

    HTML
    <script src="~/Scripts/jquery.signalR-2.4.3.min.js"></script>

    Using CDN

    Reference the library directly from CDN in the View.

    HTML
    <script src="https://cdnjs.cloudflare.com/ajax/libs/signalr.js/2.4.3/jquery.signalR.min.js"></script>
  2. Reference the auto-generated SignalR hub script for the application.

    HTML
        <script src="~/signalr/hubs"></script>
  3. Implement the initialization logic for the SignalR Hub proxy.

    JS
    <script>
        const currentUser = {
            id: '@name',
            name: 'User123',
            iconUrl: "https://demos.telerik.com/kendo-ui/content/chat/avatar.png"
        };
    
        var isTyping = false;
        var chatHub;
    
        // Start the Hub proxy and attach event handlers for the respective remote hub actions.
        $(document).ready(function () {
            chatHub = $.connection.chatHub;
    
            chatHub.client.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.client.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 connection.
            $.connection.hub.start().done(function () {
                console.log('SignalR connection started.');
            }).fail(function (err) {
                console.error('Error starting SignalR connection: ' + err.toString());
            });
        });
    </script>
  4. 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