본문으로 건너뛰기

SignalR Overview

SignalR is a real-time web application framework developed by Microsoft.

It allows developers to add real-time functionality to their web applications, providing the ability to push server-side updates to clients instantly. With SignalR, you can build applications that have real-time communication between the server and the client, enabling features such as live chat, real-time collaboration, and live updates.

History of SignalR

SignalR was first introduced by Microsoft in 2011 as an open-source library. It was initially developed for ASP.NET, but it has since evolved to support various platforms and frameworks, including ASP.NET Core. SignalR was designed to address the limitations of traditional web applications that relied on polling or long-polling techniques to achieve real-time updates. These techniques were inefficient and placed unnecessary load on the server.

Features of SignalR

  1. Real-time communication: SignalR enables real-time, bidirectional communication between the server and the client. It allows the server to push updates to connected clients instantly, eliminating the need for the client to continuously poll the server for new data.

  2. Multiple transport protocols: SignalR supports multiple transport protocols, including WebSockets, Server-Sent Events, and Long Polling. It automatically selects the most efficient transport protocol based on the capabilities of the client and server.

  3. Automatic reconnection: SignalR provides automatic reconnection capabilities, ensuring that clients can seamlessly reconnect to the server in case of network interruptions or browser refreshes.

  4. Scalability: SignalR is designed to scale horizontally, allowing you to handle a large number of simultaneous connections. It supports various backplane technologies, such as Redis and SQL Server, to distribute messages across multiple servers.

  5. Cross-platform support: SignalR can be used with various platforms and frameworks, including ASP.NET, ASP.NET Core, and even non-Microsoft technologies like Node.js.

Examples of SignalR

Example 1: Real-time chat application

Here's an example of a simple real-time chat application using SignalR:

Server-side code (C#):

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

Client-side code (JavaScript):

const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();

connection.on("ReceiveMessage", (user, message) => {
// Display the received message in the chat window
const chatWindow = document.getElementById("chatWindow");
chatWindow.innerHTML += `<p><strong>${user}</strong>: ${message}</p>`;
});

connection.start().then(() => {
// Send a message when the "Send" button is clicked
document.getElementById("sendButton").addEventListener("click", () => {
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message);
});
});

In this example, the server-side code defines a SignalR hub called "ChatHub" that exposes a method called "SendMessage". The client-side code creates a SignalR connection and registers a callback function to handle the "ReceiveMessage" event. When the user sends a message, the client invokes the "SendMessage" method on the server, which in turn broadcasts the message to all connected clients.

Example 2: Stock price updates

Here's an example of a stock price monitoring application using SignalR:

Server-side code (C#):

public class StockTicker
{
private readonly IHubContext<StockTickerHub> _hubContext;
private readonly Timer _timer;

public StockTicker(IHubContext<StockTickerHub> hubContext)
{
_hubContext = hubContext;
_timer = new Timer(UpdateStockPrices, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
}

private void UpdateStockPrices(object state)
{
// Generate random stock prices
var stocks = new Dictionary<string, decimal>
{
{ "AAPL", 150.23m },
{ "MSFT", 250.17m },
{ "GOOG", 3500.56m }
};

foreach (var stock in stocks)
{
// Send stock price updates to connected clients
_hubContext.Clients.All.SendAsync("UpdateStockPrice", stock.Key, stock.Value);
}
}
}

Client-side code (JavaScript):

const connection = new signalR.HubConnectionBuilder()
.withUrl("/stockTickerHub")
.build();

connection.on("UpdateStockPrice", (stock, price) => {
// Update the stock price in the UI
const stockPriceElement = document.getElementById(stock);
stockPriceElement.textContent = price.toFixed(2);
});

connection.start();

In this example, the server-side code periodically updates the stock prices and sends the updates to all connected clients using the "UpdateStockPrice" event. The client-side code registers a callback function to handle the event and updates the stock prices in the UI.

Conclusion

SignalR is a powerful framework that enables real-time communication between the server and the client in web applications. Its rich set of features and ease of use make it a popular choice for building real-time applications. Whether it's implementing real-time chat, live collaboration, or live updates, SignalR provides the necessary tools to create engaging and interactive web applications.

For more information about SignalR, you can refer to the official documentation here.