signalr
  1. signalr-signalrin-spas

SignalR in Single Page Applications (SPAs)

Introduction

This tutorial explores the integration of SignalR, a real-time communication library, in Single Page Applications (SPAs). SignalR enables bidirectional communication between the server and connected clients, making it well-suited for building responsive and interactive SPAs.

Using SignalR in SPAs

Syntax

Integrating SignalR into an SPA involves setting up a SignalR hub on the server and establishing a connection from the client using JavaScript. The basic syntax is as follows:

Server-Side (Hub):

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

Client-Side:

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

connection.on("ReceiveMessage", (user, message) => {
    // Handle received messages
    console.log(`${user}: ${message}`);
});

connection.start()
    .then(() => console.log("Connection established"))
    .catch(err => console.error(err));

Example

Consider a chat application where users can send and receive messages in real-time using SignalR.

Server-Side:

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

Client-Side (HTML/JavaScript):

<input type="text" id="txtUser" placeholder="Enter your name">
<input type="text" id="txtMessage" placeholder="Enter your message">
<button onclick="sendMessage()">Send Message</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.9/signalr.min.js"></script>
<script>
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chatHub")
        .configureLogging(signalR.LogLevel.Information)
        .build();

    connection.on("ReceiveMessage", (user, message) => {
        // Handle received messages
        console.log(`${user}: ${message}`);
    });

    connection.start()
        .then(() => console.log("Connection established"))
        .catch(err => console.error(err));

    function sendMessage() {
        const user = document.getElementById("txtUser").value;
        const message = document.getElementById("txtMessage").value;
        connection.invoke("SendMessage", user, message).catch(err => console.error(err));
    }
</script>

Output

The output is a chat application where messages are sent and received in real-time between connected clients.

Explanation

  • SignalR Hub: Defines the server-side hub that manages connections and message broadcasting.
  • Connection Configuration: Configures the SignalR connection on the client side.
  • Event Handling: Handles events triggered by the server (e.g., "ReceiveMessage").
  • Connection Start: Initiates the connection from the client to the SignalR hub.

Use

  • Real-Time Updates: Enable real-time updates and communication in SPAs.
  • Collaborative Editing: Support collaborative editing features in shared documents.
  • Live Notifications: Implement live notifications and alerts for users.

Important Points

  1. Ensure that the SignalR JavaScript library is included on the client side.
  2. Secure your SignalR hub and connections as needed.
  3. Be mindful of the payload size and frequency of real-time updates for optimal performance.

Summary

Integrating SignalR into SPAs enhances user experience by providing real-time communication capabilities. Whether building chat applications, collaborative tools, or live dashboards, SignalR empowers SPAs with seamless and responsive communication between the server and clients.

Published on: