푸터 콘텐츠로 바로가기
.NET 도움말

Signalr C# (How it Works For Developers)

The modern web thrives on interactivity and real-time feedback. When building responsive applications, real-time web functionality is a must. This is where SignalR shines. ASP.NET Core SignalR is a library that makes adding real-time web functionality to your applications simpler than you might think.

In this tutorial, we'll embark on a journey through the basics and nuances of SignalR. Let’s dive in!

Introduction to SignalR in ASP.NET Core

ASP.NET Core SignalR provides an API for creating real-time web functionality using WebSockets and other technologies, like server-sent events. It's not just limited to ASP.NET Core. You can use SignalR with various clients, like a browser or a mobile app, ensuring connected clients are updated instantly.

Setting Up Your Development Environment

To get started, you’ll need:

Building the SignalR Hub

At its core, SignalR revolves around a SignalR hub, a central point for both the client and the server to interact.

Create a new ASP.NET Core project. Now, add a new class and name it ChatHub. This will act as our SignalR hub.

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

// Define a SignalR Hub class named ChatHub
public class ChatHub : Hub
{
    // Asynchronous method to send messages
    public async Task SendMessage(string user, string message)
    {
        // Send a message to all connected clients
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

// Define a SignalR Hub class named ChatHub
public class ChatHub : Hub
{
    // Asynchronous method to send messages
    public async Task SendMessage(string user, string message)
    {
        // Send a message to all connected clients
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}
$vbLabelText   $csharpLabel

In the Startup class, let's integrate our hub.

public class Startup
{
    // Configure services and add SignalR
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR(); // Add SignalR services
    }

    // Configure the app to use SignalR and map the hub
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Setup endpoint to route to ChatHub
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
        });
    }
}
public class Startup
{
    // Configure services and add SignalR
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR(); // Add SignalR services
    }

    // Configure the app to use SignalR and map the hub
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Setup endpoint to route to ChatHub
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
        });
    }
}
$vbLabelText   $csharpLabel

Client Side Implementation

SignalR is versatile. While this tutorial focuses on the ASP.NET Core and the JavaScript client library, SignalR supports various clients, from .NET to Java.

Using the SignalR Client Library

The SignalR client library lets your client-side code connect and communicate directly with the server side. For our example, let's use JavaScript.

First, add the SignalR JavaScript client library:

<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@3.1.8/dist/browser/signalr.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@3.1.8/dist/browser/signalr.js"></script>
HTML

Now, you can connect to the hub:

// Create a connection to the SignalR hub
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub") // The hub URL
    .build();

// Start the connection
connection.start().catch(err => console.error(err.toString()));

// Setup a listener for receiving messages
connection.on("ReceiveMessage", (user, message) => {
    console.log(`${user} says: ${message}`);
});
// Create a connection to the SignalR hub
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub") // The hub URL
    .build();

// Start the connection
connection.start().catch(err => console.error(err.toString()));

// Setup a listener for receiving messages
connection.on("ReceiveMessage", (user, message) => {
    console.log(`${user} says: ${message}`);
});
JAVASCRIPT

This simple client-side code connects to the hub and listens for any messages broadcast.

Real-Time Functionality in Action

Sending Messages

Using our earlier client-side and server-side code snippets, sending messages is straightforward. Both the server and the client can initiate communication.

From server-side:

// Send a message from the server to all connected clients
await Clients.All.SendAsync("ReceiveMessage", "Server", "Hello from server!");
// Send a message from the server to all connected clients
await Clients.All.SendAsync("ReceiveMessage", "Server", "Hello from server!");
$vbLabelText   $csharpLabel

And from client:

// Send a message from the client to the server
connection.send("SendMessage", "Client", "Hello from client!")
    .catch(err => console.error(err.toString()));
// Send a message from the client to the server
connection.send("SendMessage", "Client", "Hello from client!")
    .catch(err => console.error(err.toString()));
JAVASCRIPT

Advanced Real-Time Communication

ASP.NET Core SignalR offers advanced real-time communication features:

  1. Grouping Connections: Segment connected clients into groups, broadcasting messages to specific segments.
  2. Handling Disconnections: Automatically manage client connections and disconnections.
  3. Binary Protocol: While SignalR uses a text-based protocol by default, it supports a binary protocol as well.

SignalR with Azure SignalR Service

For scalable real-time functionality, integrate Azure SignalR Service. This fully managed service supports massive numbers of simultaneous connections, making it ideal for high-demand apps.

Integrating Azure SignalR Service:

  1. Install the Azure SignalR SDK.
  2. Use Azure Service Bus for backplane support.
  3. Adjust the Startup class to use Azure SignalR.
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Azure SignalR services
        services.AddSignalR().AddAzureSignalR();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Use Azure SignalR and map hub with routes
        app.UseAzureSignalR(routes =>
        {
            routes.MapHub<ChatHub>("/chatHub");
        });
    }
}
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Azure SignalR services
        services.AddSignalR().AddAzureSignalR();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Use Azure SignalR and map hub with routes
        app.UseAzureSignalR(routes =>
        {
            routes.MapHub<ChatHub>("/chatHub");
        });
    }
}
$vbLabelText   $csharpLabel

Iron Suite Enhancing SignalR with Premium .NET Tools

While ASP.NET Core SignalR provides an outstanding foundation for real-time web functionality, developers often look for tools to enhance the overall experience and functionality. That's where Iron Software Suite of Libraries enters the picture.

Iron Suite is a suite of premium .NET libraries, designed to supercharge your ASP.NET Core applications, including those utilizing SignalR. Each product in this suite offers unique capabilities, ensuring a richer application experience. Let's delve into the offerings:

IronPDF

Signalr C# (How It Works For Developers) Figure 1

Learn more about IronPDF capabilities lets you generate, edit, and read PDF files within your .NET applications. Imagine integrating SignalR in a scenario where a team collaborates on a document in real-time. As changes are made, the document can be converted to a PDF on the fly, with updates pushed to all connected clients seamlessly. The real-time functionality of SignalR paired with IronPDF's capabilities could revolutionize collaborative tools.

IronPDF converts HTML, URLs, and full webpages into stunning PDFs like the original. It’s perfect for saving online reports, invoices, or any web-based information you want to keep. Are you looking to turn HTML to PDF? Try IronPDF today!

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

IronXL

Signalr C# (How It Works For Developers) Figure 2

When it comes to working with Excel spreadsheets, Explore IronXL Features is a champion. In a business setting, spreadsheets play a vital role. Incorporating SignalR alongside IronXL means that financial teams could work on budget sheets in real-time, witnessing changes as they happen. Imagine a scenario where data entries from various departments flow into a centralized Excel sheet, with real-time updates for all stakeholders. The fusion of real-time communication and dynamic spreadsheet management becomes a reality with this combination.

IronOCR

Signalr C# (How It Works For Developers) Figure 3

Optical Character Recognition (OCR) has become a staple in modern applications. See IronOCR in action empowers .NET developers to extract text from images and documents. Pairing this with SignalR's real-time functionality can be game-changing. Consider a platform where users upload images containing textual data. SignalR could be used to notify users in real-time once IronOCR processes the images, making data extraction interactive and instantaneous.

IronBarcode

Signalr C# (How It Works For Developers) Figure 4

Barcoding is integral in inventory management, ticketing systems, and more. Discover IronBarcode Capabilities simplifies the creation and reading of barcodes. Now, think of integrating this with SignalR in a warehouse management system. As items are scanned, the inventory gets updated in real-time, notifying connected clients of stock levels, and ensuring a smooth logistical operation.

Conclusion

Signalr C# (How It Works For Developers) Figure 5

The fusion of ASP.NET Core SignalR with Iron Suite's powerful tools promises an elevated experience for both developers and end-users. Real-time web functionality becomes not just about communication but a transformative tool that, when paired with the right resources like Iron Suite, can redefine interactive applications.

It's worth noting the value proposition offered by Iron Suite. Each product license starts from $799, providing developers with a premium set of features. However, if you're unsure about the immediate commitment, each product generously offers a free trial of Iron Software Products. This allows you to test-drive the capabilities before making a decision.

And, if you're considering integrating multiple tools, there's fantastic news: you can purchase the entire Iron Suite for added value for the price of just two products! This not only ensures you get the best bang for your buck but also equips you with a comprehensive toolkit to revolutionize your ASP.NET Core SignalR applications.

자주 묻는 질문

SignalR이란 무엇이며 웹 애플리케이션을 어떻게 개선하나요?

SignalR은 애플리케이션에 실시간 웹 기능을 추가하여 서버와 클라이언트 간의 즉각적인 통신을 가능하게 하는 ASP.NET Core의 라이브러리입니다. 이를 통해 실시간 업데이트와 피드백을 통해 대화형 및 반응형 웹 애플리케이션을 만들 수 있습니다.

C# 애플리케이션에서 SignalR을 설정하려면 어떻게 해야 하나요?

C# 애플리케이션에서 SignalR을 설정하려면 ASP.NET Core SDK를 설치하고 개발을 위해 Visual Studio를 사용해야 합니다. Startup 클래스에서 SignalR 서비스를 추가하고 허브를 엔드포인트에 매핑하여 서버-클라이언트 통신을 설정합니다.

실시간 커뮤니케이션에서 SignalR 허브의 역할은 무엇인가요?

SignalR 허브는 서버와 연결된 클라이언트 간의 통신을 원활하게 하는 중심 구성 요소 역할을 합니다. 실시간으로 메시지를 주고받을 수 있게 해주며 SignalR 기능의 핵심 부분입니다.

SignalR에서 실시간 메시징을 처리하려면 어떻게 해야 하나요?

SignalR의 실시간 메시징은 서버 측 허브와 클라이언트 측 스크립트를 생성하여 관리할 수 있습니다. 클라이언트 측 자바스크립트는 허브에 대한 연결을 설정하고 connection.onconnection.send와 같은 메서드를 사용하여 메시지 송수신을 처리합니다.

SignalR의 고급 기능에는 어떤 것이 있나요?

SignalR은 세그먼트 통신을 위한 연결 그룹화, 클라이언트 연결 끊김의 원활한 처리, 향상된 실시간 통신 기능을 위한 바이너리 프로토콜 지원 등의 고급 기능을 제공합니다.

Azure SignalR 서비스는 애플리케이션을 확장하는 데 어떻게 도움이 되나요?

Azure SignalR 서비스를 사용하면 많은 수의 동시 연결을 지원하여 애플리케이션을 확장할 수 있습니다. 여기에는 확장 가능한 실시간 통신을 위해 Azure의 인프라를 활용하도록 Azure SignalR SDK를 설치하고 Startup 클래스를 구성하는 것이 포함됩니다.

IronPDF를 사용하여 SignalR 애플리케이션에서 PDF를 생성하려면 어떻게 해야 하나요?

IronPDF는 SignalR 애플리케이션에서 HTML 콘텐츠를 변환하여 PDF 문서를 생성하는 데 사용할 수 있습니다. IronPDF의 RenderHtmlAsPdf 메서드를 사용하면 원활한 PDF 생성이 가능하며, 이를 SignalR의 실시간 업데이트와 통합할 수 있습니다.

IronXL은 SignalR 애플리케이션에 어떤 이점을 제공하나요?

IronXL은 Excel 파일 조작을 가능하게 하여 SignalR 애플리케이션을 향상시킵니다. 애플리케이션 내에서 Excel 문서를 만들고, 읽고, 수정할 수 있어 실시간 기능과 함께 추가적인 데이터 처리 기능을 제공합니다.

텍스트 인식을 위해 IronOCR을 SignalR 애플리케이션에 통합할 수 있나요?

예, IronOCR을 SignalR 애플리케이션에 통합하여 광학 문자 인식(OCR)을 수행할 수 있습니다. 이를 통해 이미지에서 실시간 텍스트 추출이 가능하여 동적 텍스트 인식 기능으로 애플리케이션을 향상시킬 수 있습니다.

SignalR 애플리케이션에서 IronBarcode를 사용하면 어떤 잠재력이 있나요?

IronBarcode는 SignalR 애플리케이션에서 실시간으로 바코드를 생성하고 판독하는 데 사용할 수 있습니다. 이 기능은 동적 바코드 처리와 실시간 데이터 처리가 필요한 애플리케이션에 유용합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.