LESSON 2 OF 14

2. Building the First Hub and JavaScript Client-Server Communication

Learn how to create a basic SignalR Hub, configure the JavaScript client, and implement real-time message sending, receiving, and connection management.

50 dk 57

Introduction

In the previous lesson, we examined the general SignalR architecture, the role of a Hub, and the difference between real-time communication and the traditional HTTP request-response model. In this lesson, we will build a working example. The goal is to send a message from a browser to a server-side Hub method and then broadcast that message from the Hub to connected clients in real time.

Our example will be a small announcement area. A user will enter a name and a message, the JavaScript client will send those values to the Hub, and the Hub will publish the message to every connected client. By opening the application in two browser tabs, you can observe real-time communication without refreshing either page.

In this application, the Hub is the server-side class that accepts calls from clients and sends calls to clients. The JavaScript client uses connection.on to listen for server-to-client calls and connection.invoke to call a method on the server-side Hub.

Preparing the sample application

First, register SignalR services and map the Hub endpoint in the ASP.NET Core application. This example assumes a simple ASP.NET Core application using Razor Pages or MVC.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddSignalR();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapRazorPages();
app.MapHub<AnnouncementHub>("/hubs/announcement");

app.Run();

AddSignalR registers the services required by the Hub infrastructure. MapHub defines the URL that clients use to connect. In this example, the Hub endpoint is /hubs/announcement. The JavaScript client must use the same path when creating its connection.

Creating the first Hub class

Create an AnnouncementHub.cs file in a Hubs folder. A Hub class derives from Microsoft.AspNetCore.SignalR.Hub.

using Microsoft.AspNetCore.SignalR;

namespace RealtimeDemo.Hubs;

public class AnnouncementHub : Hub
{
    public async Task PublishAnnouncement(string user, string message)
    {
        if (string.IsNullOrWhiteSpace(user))
        {
            throw new HubException("User name cannot be empty.");
        }

        if (string.IsNullOrWhiteSpace(message))
        {
            throw new HubException("Message cannot be empty.");
        }

        await Clients.All.SendAsync(
            "AnnouncementReceived",
            user.Trim(),
            message.Trim(),
            DateTimeOffset.UtcNow);
    }

    public Task<string> Ping(string value)
    {
        return Task.FromResult($"Server received: {value}");
    }
}

PublishAnnouncement is a Hub method that can be invoked by a client. Because the method uses Clients.All, the announcement is sent to every connected client, including the client that initiated the call. The first argument passed to SendAsync, AnnouncementReceived, is the client method name that JavaScript will listen for. The name must match on both sides.

The Ping method demonstrates how a Hub method can return a value. When the JavaScript client invokes this method, the resulting Promise completes with the string returned by the server. This is useful when the client needs a response or validation result rather than a simple broadcast.

Adding the JavaScript client

The SignalR JavaScript client can be added through npm, LibMan, or a CDN. In an ASP.NET Core application, use a current SignalR JavaScript client package and make the client file available to the application’s static file pipeline. The exact package workflow depends on the project structure.

For this lesson, assume that the browser can access the global signalR object. In a Razor view or HTML page, the SignalR client library must be loaded before the application code. Keeping the connection logic in a separate file such as announcement.js makes the code easier to maintain and test.

The page body can contain the following elements:

<main>
    <h2>Announcements</h2>

    <label for="userInput">Name</label>
    <input id="userInput" type="text" maxlength="50" />

    <label for="messageInput">Message</label>
    <input id="messageInput" type="text" maxlength="250" />

    <button id="sendButton" type="button">Send</button>
    <button id="stopButton" type="button">Disconnect</button>

    <p id="connectionStatus">Waiting for connection...</p>
    <ul id="announcementList"></ul>
</main>

Creating the Hub connection

Now configure the JavaScript client. HubConnectionBuilder creates the connection object. withUrl specifies the Hub endpoint, while configureLogging controls the detail written to the browser console.

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

const userInput = document.getElementById("userInput");
const messageInput = document.getElementById("messageInput");
const sendButton = document.getElementById("sendButton");
const stopButton = document.getElementById("stopButton");
const connectionStatus = document.getElementById("connectionStatus");
const announcementList = document.getElementById("announcementList");

The connection object has not connected to the server yet. build only creates the client-side connection object. The actual connection is established later by calling connection.start().

Listening for messages from the server

The Hub code shows that the server will call a client method named AnnouncementReceived. Register this handler before starting the connection. This ensures that the client is ready to process messages as soon as the connection becomes active.

connection.on("AnnouncementReceived", (user, message, createdAt) => {
    const item = document.createElement("li");
    const date = new Date(createdAt).toLocaleTimeString();

    item.textContent = `[${date}] ${user}: ${message}`;
    announcementList.appendChild(item);
});

The first argument passed to connection.on must match the name used in the Hub’s SendAsync call. The parameter order must also match the order used by the server. Using textContent instead of innerHTML prevents user-provided text from being interpreted as HTML.

Starting the connection

Starting a connection is asynchronous, so call start from an async function. The Send button can remain disabled until the connection is ready.

async function startConnection() {
    sendButton.disabled = true;
    connectionStatus.textContent = "Connecting...";

    try {
        await connection.start();
        connectionStatus.textContent = "Connected";
        sendButton.disabled = false;
        console.log("SignalR connection established.");
    } catch (error) {
        connectionStatus.textContent = "Connection failed";
        console.error("SignalR connection error:", error);
    }
}

startConnection();

If start fails, its Promise is rejected. That is why a try/catch block is important. During development, the browser console can help identify an incorrect Hub URL, an HTTPS configuration problem, or a server that is not running.

Invoking a Hub method from the client

When the user clicks Send, call the PublishAnnouncement method. The invoke method waits for the server method to complete and reports an error if the server throws one.

sendButton.addEventListener("click", async () => {
    const user = userInput.value.trim();
    const message = messageInput.value.trim();

    if (!user || !message) {
        connectionStatus.textContent = "Name and message are required.";
        return;
    }

    try {
        await connection.invoke("PublishAnnouncement", user, message);
        messageInput.value = "";
        connectionStatus.textContent = "Message sent.";
    } catch (error) {
        console.error("Message could not be sent:", error);
        connectionStatus.textContent = "An error occurred while sending.";
    }
});

The method name and parameter order must match the Hub definition. When invoke is used, the client can receive the return value of the server method. If the client does not need a return value or server-side exception, send can be used instead. However, send does not wait for a return value or for errors produced by the server method.

Receiving a result from the server

The Ping method can be tested from a button or directly from the browser console:

async function testPing() {
    try {
        const result = await connection.invoke("Ping", "Hello");
        console.log(result);
    } catch (error) {
        console.error("Ping error:", error);
    }
}

The console should display a result similar to Server received: Hello. This demonstrates that SignalR is not limited to one-way notifications. A client can invoke a Hub method and receive a value after the server finishes processing it.

Stopping the connection

When a user leaves the page or the application no longer needs real-time communication, the connection can be stopped. Use the stop method for this purpose.

stopButton.addEventListener("click", async () => {
    try {
        await connection.stop();
        connectionStatus.textContent = "Connection stopped.";
        sendButton.disabled = true;
    } catch (error) {
        console.error("Connection could not be stopped:", error);
    }
});

connection.onclose(error => {
    sendButton.disabled = true;
    connectionStatus.textContent = error
        ? "Connection closed because of an error."
        : "Connection stopped.";

    console.log("Connection closed:", error);
});

The onclose callback runs when the connection closes. Automatic reconnection is not the main focus of this lesson; it will be examined in more detail later. At this stage, the important point is that the connection lifecycle includes startup, active communication, and graceful shutdown.

Inspecting browser and server logs

Run the application and open it in two browser tabs. Open the Console panel in the developer tools of both tabs. When you send an announcement from one tab, the Hub uses Clients.All to send it to both tabs. A new list item should appear in each tab without a page refresh.

To make server logging more visible during development, console logging can be enabled:

builder.Logging.AddConsole();

Setting the SignalR client log level to LogLevel.Information or, when diagnosing a difficult issue, LogLevel.Trace, can reveal connection and transport details. Trace logging can produce a large amount of output, so use it carefully outside development.

Common mistakes

  • Mismatched Hub URL: If the server maps MapHub<AnnouncementHub>("/hubs/announcement") but the client uses another URL, the connection will fail.
  • Registering handlers too late: Register connection.on handlers before starting the connection so that early messages are not missed.
  • Incorrect method names: Treat AnnouncementReceived and announcementReceived as different names. Keep naming consistent.
  • Incorrect argument order: If the server sends user, message, createdAt, the client should expect the same order.
  • Ignoring asynchronous errors: start, invoke, and stop are asynchronous operations. Handle failures with try/catch.
  • Unsafe HTML insertion: Prefer textContent when displaying user messages instead of inserting them with innerHTML.
  • Invoking before connection: Calling invoke before the connection is established can fail. Keep controls synchronized with the connection state.

Short practice exercise

Extend the sample application with the following exercise:

  1. Add a SendToCaller method to AnnouncementHub.
  2. Use Clients.Caller.SendAsync so the method sends the message only to the client that invoked it.
  3. Add a second button that invokes the new method from JavaScript.
  4. Display broadcast messages and caller-only messages in separate lists.
  5. Open two browser tabs and verify which messages appear in both tabs and which appear only in the initiating tab.
  6. Test empty names and empty messages to confirm that both client-side and Hub-side validation behave as expected.

Conclusion

In this lesson, we built our first working SignalR scenario. We registered SignalR services, defined a Hub class, sent a message from the Hub to all connected clients, and listened for that message in a JavaScript client. We also invoked a Hub method from the client, received a server response, started the connection, and stopped it in a controlled way.

The communication model in this example was a simple broadcast to everyone. Real applications often need messages for specific users or groups, authentication, reconnection, and more detailed error handling. In the next lessons, we will improve the message flow and establish more structured client-server communication patterns.

Sources