How to Build Your First SignalR Chat Application?


How to Build Your First SignalR Chat Application?

SignalR is a powerful library developed by Microsoft that stands out for developing real-time web applications. Especially for developers seeking answers to the question "How to Build Your First SignalR Chat Application?", SignalR offers high performance in scenarios like live chat applications. In this article, the use of SignalR to create a basic chat application will be explained step by step and with example code.

What is SignalR and Why Is It Used?

SignalR was developed to facilitate real-time, two-way data communication between server and client. Unlike standard HTTP requests, not only the client sends requests to the server; the server can also instantly send messages to the client. When setting out with the title "How to Build Your First SignalR Chat Application?", it is clear why this technology is preferred for real-time messaging: It can automatically use infrastructures such as WebSocket, Server-Sent Events, and Long Polling.

Step-by-Step First SignalR Chat Application

1. Project Setup

First, open an empty ASP.NET Core project and add the Microsoft.AspNetCore.SignalR package via NuGet. Then, define a ChatHub class:


using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

2. Defining the SignalR Connection

Let's add the SignalR service and specify our route in Startup.cs or Program.cs:


builder.Services.AddSignalR();
app.MapHub<ChatHub>("/chatHub");

3. Chat Client with Simple HTML and JavaScript

Below is a very simple HTML frontend example integrated with SignalR. Don't forget to add the signalr.js library to your project.


<!DOCTYPE html>
<html>
<head>
  <title>SignalR Chat Application</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>
</head>
<body>
  <input type="text" id="userInput" placeholder="Name" />
  <input type="text" id="messageInput" placeholder="Your message" />
  <button onclick="sendMessage()">Send</button>
  <ul id="messagesList"></ul>
  <script>
    const connection = new signalR.HubConnectionBuilder()
      .withUrl("/chatHub")
      .build();

    connection.on("ReceiveMessage", (user, message) => {
      const li = document.createElement("li");
      li.textContent = `${user}: ${message}`;
      document.getElementById("messagesList").appendChild(li);
    });

    connection.start();

    function sendMessage() {
      const user = document.getElementById("userInput").value;
      const message = document.getElementById("messageInput").value;
      connection.invoke("SendMessage", user, message);
    }
  </script>
</body>
</html>

Conclusion and Recommendations

This example given to answer the question "How to Build Your First SignalR Chat Application?" shows the simplest way to use SignalR in real-time web applications. This basic application can be a starting point for more advanced chat applications or live notification systems. It is recommended to review the SignalR documentation for requirements like security, authentication, and connection management.