.NET

.NET SignalR Console Client demo

2022-10-09  本文已影响0人  Charles2018
using Microsoft.AspNetCore.SignalR.Client;

HubConnection connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:44394/hub/chat", options =>
                {
                    options.AccessTokenProvider = async () =>
                    {
                        var accessToken = await File.ReadAllTextAsync("accessToken.txt");
                        return accessToken;
                    };
                })
                .WithAutomaticReconnect()
                .Build();

connection.Closed += async (error) =>
{
    Console.WriteLine("Connection closed...");
    await Task.Delay(new Random().Next(0, 5) * 1000);
    await connection.StartAsync();
};

connection.Reconnecting += error =>
{
    if(connection.State == HubConnectionState.Reconnecting)
    {
        Console.WriteLine("Reconnecting...");
    }
    return Task.CompletedTask;
};

connection.On<string, string>("ReceiveMessage", (user, message) =>
{
    Console.WriteLine($"ReceiveMessage from {user}: {message}");
});
await connection.StartAsync();
Console.WriteLine("Connection started...");


var cmd = "";
do
{
    Console.Write("Enter message to send: ");
    cmd = Console.ReadLine()!;
    await connection.InvokeAsync("SendMessageToAllUser","1123",cmd);
}while(cmd.StartsWith("quite") != true);
上一篇 下一篇

猜你喜欢

热点阅读