Of course! To test a SignalR connection from Node.js, you need two parts:
- A SignalR Server: The client needs something to connect to. We'll create a minimal one using ASP.NET Core.
- A Node.js Client: This will use the official
@microsoft/signalr package to connect, register, send, and receive messages.
Here is a complete, step-by-step guide.
Part 1: The SignalR Server (using ASP.NET Core)
If you already have a SignalR server, you can skip this part and adapt the Node.js client to your existing Hub methods. If not, follow these steps to create a simple test server.
1. Create a new ASP.NET Core Web API project:
You'll need the .NET SDK installed.
dotnet new webapi -n SignalRServer
cd SignalRServer
2. Create a ChatHub.cs file:
This file defines the server-side methods that your Node.js client will call.
// ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
// Client calls this method to "register" by sending its name
public async Task RegisterUser(string username)
{
// You could store this user info if needed
// For now, just broadcast that a new user has joined
await Clients.All.SendAsync("ReceiveMessage", "SYSTEM", $"{username} has joined the chat.");
}
// Client calls this to send a message to everyone
public async Task SendMessage(string user, string message)
{
// Broadcast the received message to all clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
// You can also define methods to handle disconnection automatically
public override async Task OnDisconnectedAsync(Exception? exception)
{
// You would need a way to know which user disconnected.
// For a real app, you'd map ConnectionId to a username.
await Clients.All.SendAsync("ReceiveMessage", "SYSTEM", $"A user has left the chat.");
await base.OnDisconnectedAsync(exception);
}
}
Key Server Methods:
RegisterUser(username): A custom method for a client to identify itself.
SendMessage(user, message): A method to broadcast a message.
ReceiveMessage: This is not a server method. It's the name of the client-side function the server will call.
3. Modify Program.cs to enable SignalR and CORS:
Replace the content of Program.cs with the following to configure the services.
var builder = WebApplication.CreateBuilder(args);
// 1. Add SignalR service
builder.Services.AddSignalR();
// 2. Add CORS policy to allow your Node.js client (or any client)
// to connect. THIS IS CRUCIAL FOR TESTING.
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true) // Allows any origin
.AllowCredentials();
});
});
var app = builder.Build();
// Use the CORS policy
app.UseCors("AllowAll");
// Standard middleware
app.UseHttpsRedirection();
// 3. Map the Hub to an endpoint
app.MapHub<ChatHub>("/chathub");
app.Run();
4. Run the server:
In your terminal, inside the SignalRServer directory, run:
dotnet run
Your SignalR hub will now be running and accessible at https://localhost:7123/chathub (the port may vary, check your terminal output).
Part 2: The Node.js Client
Now, let's create the Node.js script that connects to this server.
1. Set up a new Node.js project:
mkdir signalr-node-client
cd signalr-node-client
npm init -y
npm install @microsoft/signalr
2. Create the client script (client.js):
This script will connect to the hub, register a user, listen for messages, and allow you to send messages from the console.
// client.js
const signalR = require("@microsoft/signalr");
const readline = require("readline");
// --- Configuration ---
// Make sure this URL matches the one from your ASP.NET Core server output.
// If your server uses HTTP instead of HTTPS, change the URL accordingly.
const hubUrl = "https://localhost:7123/chathub"; // Use the correct port!
const username = `NodeClient_${Math.floor(Math.random() * 100)}`;
// If your server has a self-signed certificate (common in development),
// you might need to disable SSL verification.
// WARNING: Only do this for local development and testing.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
// --- Connection Setup ---
const connection = new signalR.HubConnectionBuilder()
.withUrl(hubUrl)
.withAutomaticReconnect() // Automatically tries to reconnect if the connection is lost
.configureLogging(signalR.LogLevel.Information)
.build();
// --- Define Client-Side Event Handlers ---
// This is how the server invokes methods on your client.
// The name 'ReceiveMessage' must match the string used in the server's SendAsync call.
connection.on("ReceiveMessage", (user, message) => {
console.log(`\n[${user}]: ${message}`);
promptForMessage(); // Re-display the input prompt
});
connection.onclose(error => {
console.log("Connection closed. Attempting to reconnect...", error);
});
// --- Main Logic ---
async function start() {
try {
console.log("Connecting to SignalR Hub...");
await connection.start();
console.log("Connection successful! Connection ID:", connection.connectionId);
// 1. REGISTER THE USER
// Call the 'RegisterUser' method on the server's Hub.
await connection.invoke("RegisterUser", username);
console.log(`Registered as '${username}'. You can now send messages.`);
// Start the interactive message sending loop
promptForMessage();
} catch (err) {
console.error("Connection failed: ", err);
setTimeout(start, 5000); // Retry connection after 5 seconds
}
}
// --- Interactive Console for Sending Messages ---
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function promptForMessage() {
rl.question("Enter message > ", async (message) => {
if (message.toLowerCase() === "exit") {
await connection.stop();
rl.close();
return;
}
try {
// 2. SEND A MESSAGE
// Call the 'SendMessage' method on the server's Hub.
await connection.invoke("SendMessage", username, message);
} catch (err) {
console.error("Error sending message: ", err);
}
// The prompt will be re-displayed after the server broadcasts the message back
});
}
// Start the application
start();
Part 3: How to Run and Test
-
Start the Server: In one terminal, navigate to the SignalRServer directory and run:
dotnet run
You should see output indicating the server is listening on a specific URL (e.g., https://localhost:7123).
-
Start the Client: In a second terminal, navigate to the signalr-node-client directory and run:
node client.js
Expected Behavior:
-
Node.js Client Terminal:
- It will connect to the hub.
- It will "register" by sending its generated username.
- You will see a
[SYSTEM]: NodeClient_XX has joined the chat. message, which was broadcast by the server.
- You will see an
Enter message > prompt.
-
Testing:
- In the Node.js terminal, type
Hello from Node! and press Enter.
- The message is sent to the server via
invoke("SendMessage", ...).
- The server receives it and broadcasts it back to all clients using
SendAsync("ReceiveMessage", ...).
- Your Node.js client will receive this broadcast and print
[NodeClient_XX]: Hello from Node! to the console.
-
Test with a Browser Client (Optional):
- You can open your browser and navigate to the same server URL (
https://localhost:7123/chathub). While you won't see anything by default, this will trigger the connection/disconnection events on the server, which you can see in your Node.js client's log. If you build a simple HTML/JS front-end, you can have a browser and your Node.js script talk to each other.