signalr
  1. signalr-signalrin-aspnet-core

SignalR in ASP.NET Core

Syntax

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

Example

SignalR is a real-time communication library that enables bi-directional communication between server and client. It is very useful in creating web applications that require real-time updates such as chat applications, stock market applications, etc.

In this example, we will create a chat application using SignalR in ASP.NET Core. Here, we will implement a simple functionality where users can join different chat rooms and send and receive messages in real-time.

Output

SignalR in ASP.NET Core Output

Explanation

To implement this feature, we first need to create a SignalR Hub that will act as a communication channel between the server and clients. In the above code, we have created a ChatHub class that derives from the Hub class.

We have defined a SendMessage method that takes two parameters, user and message. This method sends a message to all the connected clients by calling the Clients.All.SendAsync method.

In the client-side, we have created a JavaScript function called sendMessage that reads the user's input and sends the message to the server by calling the ChatHub's sendMessage method.

Use

SignalR is very useful in creating web applications that require real-time updates such as chat applications, stock market applications, etc.

It allows us to create real-time web applications using technologies like WebSockets, server-sent events, long-polling, etc.

Important Points

  • SignalR is a real-time communication library that enables bi-directional communication between server and client.
  • SignalR is useful in creating web applications that require real-time updates.
  • SignalR can be used with various real-time communication protocols.
  • SignalR can communicate with clients using various channels such as WebSockets, server-sent events, long-polling, etc.

Summary

In this article, we have learned about SignalR in ASP.NET Core. We have seen how to create a chat application using SignalR and how it can be used to create real-time web applications. We have also learned about its important features and concepts.

Published on: