Hello everyone, I hope you have a day full of energy.
Today, I will introduce the SignalR topic in .NET. What is a real-time application? What is SignalR in .NET? The main concepts in SignalR. How to use SignalR to build a simple chat application.
I hope to engage in some fruitful discussions with you all. Without further ado, let’s get started.
1. What is the real-time application?
A real-time application is a type of application that delivers and processes information for users immediately, without significant waiting.
Some common real-time applications include:
– Online Chat: Real-time chat applications where users can send and receive messages without the need to reload the page.
– Dashboards and monitoring apps: Display real-time information such as data from sensors, financial market data, or system notifications.
– Notification apps: Applications that require system notifications such as social networks, email, chat, games, travel alerts, and more.
– And various other types of applications. Refer to the additional image below for more information.
2. What is SignalR?
Real-time application is a type of application that delivers and processes information for users immediately, without significant waiting.
SignalR provides several key features that make it a popular choice for building real-time web applications. Here are some of the main features:
– Real-time Communication: SignalR enables real-time communication between the server and connected clients, allowing immediate updates and interactions without the need for clients to poll the server continuously.
– Bi-Directional Communication: SignalR supports both server-to-client and client-to-server communication. This bidirectional communication is essential for scenarios where updates can originate from either end.
– Multiple Transport Protocols:SignalR supports multiple transport protocols, including WebSockets, Server-Sent Events (SSE), long polling, and more. This ensures compatibility with various browsers and network configurations, allowing the framework to choose the most appropriate transport method.
– Hubs for Abstraction:Hubs provide a high-level abstraction for organizing communication between clients and servers. They simplify the process of managing connections and invoking methods on clients. Hubs enable developers to structure their real-time communication logic in a more organized manner.
– Cross-platform Compatibility: While SignalR has its roots in the ASP.NET framework, it has been expanded to support cross-platform development. It can be used with both .NET and non-.NET environments, making it versatile for different types of applications.
– Scalability: SignalR is designed to scale horizontally, allowing applications to handle a large number of simultaneous connections. It supports scaling across multiple servers, making it suitable for applications with high traffic and concurrency requirements.
– Connection Persistence: SignalR provides connection persistence, allowing clients to reconnect automatically in case of network disruptions or
– changes. This ensures a more robust and resilient real-time communication experience.
– Built-in Security: SignalR includes built-in security features, such as support for authentication and authorization. This ensures that only authorized users can connect to the server and access specific real-time communication channels.
– Automatic Reconnection: SignalR handles automatic reconnection for clients, making it more fault-tolerant. If a client loses its connection, SignalR attempts to reconnect automatically, maintaining the continuity of real-time updates.
Are you ready to take your web applications to the next level? Dive into the world of real-time communication with ASP.NET and SignalR! Stay ahead of the curve with dynamic, interactive experiences that keep users engaged and informed in real-time. Explore the possibilities with our Web Application Development Services!
We will go into detail for each feature in the next section.
3. SignalR Transports type
SignalR Transports types are mechanisms or protocols used to establish and maintain connections between clients and servers. SignalR supports various transport methods to ensure flexibility and compatibility across different environments. Here are some common types of transports in SignalR:
– WebSockets: a protocol that provides a continuous connection for sending and receiving bidirectional data between clients and servers. Applications like online chat, real-time dashboards, and integrated system notifications utilize WebSockets
Server-Sent Events (SSE): SSE is a protocol where the server can automatically send events and new data to the client. It is a one-way transport, with the client unable to send data to the server. Suitable for applications such as updating sports events and online entertainment information to users.
Long Polling: Long Polling is a technique where the client sends a request to the server, and the server keeps the connection open until there is new data or a timeout occurs. Afterward, the client and server establish a new connection. SignalR with Long Polling transport is often used in situations where maintaining a continuous connection is not a priority but real-time functionality is still needed. Long Polling is employed when other transports like WebSockets or Server-Sent Events are unavailable or unsuitable. While it may introduce latency compared to full transports, it still provides real-time functionality without requiring a constant connection.
Configuring the transport type for SignalR in .NET. The default transport type is WebSocket.
4. Hubs in SignalR
A Hub is a server-side object that provides a centralized way for bidirectional communication between clients and the server. Hubs enable the transmission of messages from the server to clients and vice versa, creating a real-time communication model among different components of a web application.
The key features of SignalR Hubs, which facilitate real-time communication between the server and connected clients, include:
– Centralized Communication: Hubs serve as a centralized point for bidirectional communication, allowing clients to interact with each other and the server through the hub.
– Hub Methods: Developers define methods on the server hub that can be called by clients, and vice versa. This makes it easy to invoke server-side logic from clients and vice versa.
– Automatic Serialization: SignalR Hubs automatically handle the serialization and deserialization of messages, simplifying the process of passing complex data structures between the server and clients.
– Groups: Hubs support the concept of groups, allowing clients to join specific groups. This enables targeted message broadcasting to members of a particular group.
– Connection Lifecycle Events: Hubs provide methods that are called when clients connect or disconnect from the hub. This feature allows for additional logic to be executed during these connection lifecycle events.
– Built-in Transports Abstraction: Hubs abstract away the details of underlying transport mechanisms, supporting various transport protocols such as WebSockets, Server-Sent Events (SSE), and long polling.
– State Management: Hubs allow developers to manage state across connections, making it possible to track information about clients and maintain application state.
– Reconnection Handling: SignalR Hubs handle client reconnections seamlessly, ensuring continuity in real-time communication even if a client temporarily loses connection.
5. Group in SignalR
Group is a concept that helps organize and manage connections of clients. Each group has a unique name, and connections can join or leave the group. Using groups allows sending messages to all members within a group, managing the group’s state, and facilitating interactions among its members.
There are the basic methods of a group:
– AddToGroupAsync / RemoveFromGroupAsync
SendToGroupAsync
GroupExcept (JavaScript client)
GroupAdd / GroupRemove (JavaScript client)
UserGroups (JavaScript client)
6. Typical flow
We create a signalR Hub
We configure SignalR in startup.cs class
We add client side SignalR
We connect client with SignalR
We handle hub events
We invoke hub method
7. connection.invoke and connection.send, Clients.All and Clients.Client
Invoke is used when you want to send a request from the client to the server and receive the result back from the server. It returns a Promise, allowing you to use async/await to handle the result.
Send is used when you want to send a request from the client to the server but do not expect an immediate response from the server. It does not return a Promise.
The choice between invoke and send depends on the specific requirements of the application. If you need to know the result of the request (such as sending a message and receiving a confirmation), you should use invoke. Conversely, if the request does not require immediate feedback, send might be a better choice to reduce latency and improve performance
8. Building a simple chat application with SignalR
We create ChatHub
We config SignalR
We create Client UI and handle Client to connect with SignalR Hub
– https://github.com/saigontechnology/Blog-Resources/blob/main/DotNet/long.nguyendh/SignalRSample/Views/Home/Chat.cshtml
– https://github.com/saigontechnology/Blog-Resources/blob/main/DotNet/long.nguyendh/SignalRSample/wwwroot/js/chat.js
Resources:
– https://github.com/saigontechnology/Blog-Resources/tree/main/DotNet/long.nguyendh
References: