.NET Clients - SignalR Clients
Syntax
using Microsoft.AspNetCore.SignalR.Client;
var connection = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/chathub")
.Build();
Example
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Threading.Tasks;
namespace SignalR_Client_Demo
{
class Program
{
static async Task Main(string[] args)
{
var connection = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/chathub")
.Build();
connection.On<string, string>("ReceiveMessage", (user, message) =>
{
Console.WriteLine($"{user}: {message}");
});
await connection.StartAsync();
Console.WriteLine("Enter your name:");
var user = Console.ReadLine();
Console.WriteLine($"Welcome {user}!");
while (true)
{
Console.WriteLine("Enter a message:");
var message = Console.ReadLine();
await connection.InvokeAsync("SendMessage", user, message);
}
}
}
}
Output
The output will be the received message in the console.
Explanation
.NET SignalR Clients provide a way to communicate with a SignalR hub from a .NET client application. The above code snippet shows how to connect to a SignalR hub using a HubConnectionBuilder and send and receive messages.
Use
This code can be used to connect a .NET client application to a SignalR hub and send and receive messages between the client and the server.
Important Points
- The WithUrl method in the HubConnectionBuilder is used to specify the URL of the SignalR hub to connect to.
- The connection.On method is used to specify a callback function to be executed when a message is received from the server.
- The await connection.StartAsync() method must be called before sending or receiving messages.
- The connection.InvokeAsync method is used to send a message to the server.
Summary
.NET SignalR Clients provide a simple and efficient way to communicate with SignalR hubs from .NET client applications. The HubConnectionBuilder allows for easy configuration of the connection to the hub, and the connection.On and connection.InvokeAsync methods provide easy ways to send and receive messages.