Examples
.NET Real-Time Chat
Building a Real-Time Chat
.NET real-time chat uses SignalR for WebSocket messaging.
Introduction to SignalR in .NET
SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality enables server-side code to push content to clients instantly as it becomes available, rather than having the server wait for a client to request new data.
SignalR provides a simple API for creating server-to-client remote procedure calls (RPCs) in ASP.NET. It uses WebSockets under the hood when available, and falls back on other technologies when it isn't, making it a robust choice for real-time applications.
Setting Up a .NET Core Project
To get started with SignalR in a .NET Core application, you'll first need to set up a new project. Use the following command to create a new ASP.NET Core web application:
This command creates a new web application named RealTimeChatApp. After creating the project, you need to add the SignalR package to it:
Configuring SignalR
Next, you'll need to set up SignalR in your application. Open the Startup.cs
file and modify it as follows:
In the above code, services.AddSignalR()
is added to the service collection to enable SignalR. In the Configure
method, app.UseEndpoints
is used to map the SignalR hub to the path /chatHub
.
Creating the SignalR Hub
A SignalR hub is a class that serves as the main coordination point for SignalR connections. Create a new class named ChatHub
in your project:
The ChatHub
class inherits from Hub
and includes a method named SendMessage
that can be called by connected clients. It uses the Clients.All.SendAsync
method to send the received message to all connected clients.
Implementing the Client Side
To interact with the SignalR hub, you'll need to implement client-side code. Add the SignalR client library by including a reference to the SignalR JavaScript file in your HTML:
Next, establish a connection to the ChatHub
and handle sending and receiving messages:
The code above sets up a SignalR connection to the /chatHub
and listens for messages on the ReceiveMessage
event. When a message is received, it is displayed in the messagesList
element.
Examples
- Previous
- Database CRUD
- Next
- Razor Page App