# Peer-to-Peer Chat

You can configure the Telerik UI Chat component for ASP.NET Core and a [ASP.NET Core SignalR](https://docs.microsoft.com/en-us/aspnet/core/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-core-examples/blob/master/Telerik.Examples.Mvc/Telerik.Examples.Mvc/Views/Chat/ChatPeerToPeer.cshtml).

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

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

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

    <kendo-chat name="chat"
        author-id="@name"
        is-typing-field="isTyping"
        on-send-message="onSendMessage"
        on-input="onInput">
    </kendo-chat>
```

```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.invoke("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.invoke("send", args.message.authorId, args.message.authorName, args.message.text);
    }
</script>
```

## 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 View
   <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

* [Basic Usage of the Chat for ASP.NET Core (Demo)](https://demos.telerik.com/aspnet-core/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-core-ui/documentation/api/chat)

* [Server-Side API of the Chat TagHelper](https://www.telerik.com/aspnet-core-ui/documentation/api/taghelpers/chat)
