# Peer-to-Peer Chat

You can configure the Telerik UI Chat component for ASP.NET MVC and a [SignalR 2](https://www.asp.net/signalr) service to create a Peer-to-Peer Chat application.

For the complete project, refer to the [Chat Peer to Peer example](https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/Telerik.Examples.Mvc/Telerik.Examples.Mvc/Areas/ChatPeerToPeer).

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](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/conversational-ui/chat/signalr-p-to-p#creating-the-new-application)
2. [Configure the SignalR Hub server](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/conversational-ui/chat/signalr-p-to-p#configuring-the-signalr-hub-server)
3. [Initialize the Chat](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/conversational-ui/chat/signalr-p-to-p#initializing-the-chat)
4. [Configure the SignalR client Hub proxy](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/conversational-ui/chat/signalr-p-to-p#configuring-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 MVC application from the Standard template](https://www.telerik.com/aspnet-mvc/documentation/vs-integration/new-project-wizard)
* [Create a new ASP.NET MVC application in Visual Studio and include the Telerik UI for ASP.NET MVC package](https://www.telerik.com/aspnet-mvc/documentation/getting-started-mvc/first-steps)

## Configuring the SignalR Hub Server

1. Add the[ `Microsoft.AspNet.SignalR`](https://www.nuget.org/packages/Microsoft.AspNet.SignalR) NuGet package to the application.

   ```powershell
   Install-Package Microsoft.AspNet.SignalR
   ```

2. Create a `Startup.cs` file to configure the hub connection.

   ```C# Startup.cs
       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.

   ```C# ChatHub.cs
       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`](https://www.telerik.com/aspnet-mvc/documentation/api/kendo.mvc.ui.fluent/chateventbuilder#sendmessagesystemstring) and [`Input`](https://www.telerik.com/aspnet-mvc/documentation/api/kendo.mvc.ui.fluent/chateventbuilder#inputsystemstring) events.

```Razor HtmlHelper
    @{
        var name = Guid.NewGuid().ToString();
    }

    @(Html.Kendo().Chat()
        .Name("chat")
        .AuthorId(@name)
        .IsTypingField("isTyping")
        .Events(events => events
            .Input("onInput")
            .SendMessage("onSendMessage")
        )
    )
```

```JS Scripts
<script>
    const currentUser = {
        id: '@name',
        name: 'User123',
        iconUrl: "https://demos.telerik.com/kendo-ui/content/chat/avatar.png"
    };
    let isTyping = false;

    // The 'Input' will notify the SignallR Hub that the current client is typing.
    // The Hub, in turn, will notify all the other clients that the user has started typing.
    function onInput(e) {
        // If not already typing, send typing notification.
        if (!isTyping) {
            isTyping = true;
            chatHub.server.sendTyping(currentUser.id, currentUser.name);
        }
    }

    // The 'SendMessage' handler will send the user data and the typed text to the SignalR Hub.
    // The Hub will then forward that info to the other clients.
    function onSendMessage(args) {
        // Update the message data based on the current user's data.
        args.message.id = kendo.guid();
        args.message.authorId = currentUser.id;
        args.message.authorName = currentUser.name;
        args.message.authorImageUrl = currentUser.iconUrl;

        // Stop typing when sending a message.
        if (isTyping) {
            isTyping = false;
        }
        chatHub.server.send(args.message.authorId, args.message.authorName, args.message.text);
    }
</script>
```

## Configuring the SignalR Client Hub Proxy

1. Include the SignalR 2 script in the page. You can install [`Microsoft.AspNet.SignalR.JS`](https://www.nuget.org/packages/microsoft.aspnet.signalr.js/) NuGet package or reference the library directly from CDN.

   **Using NuGet package**

   ```powershell
   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

* [Basic Usage of the Chat for ASP.NET MVC (Demo)](https://demos.telerik.com/aspnet-mvc/chat/index)
* [Client-Side API of the Chat](https://docs.telerik.com/kendo-ui/api/ui/chat)
* [Server-Side API of the Chat](https://www.telerik.com/aspnet-mvc/documentation/api/chat)
