美文网首页.NET
.NET SignalR Console Client demo

.NET SignalR Console Client demo

作者: 老中医167788 | 来源:发表于2022-10-09 14:13 被阅读0次
    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);
    

    相关文章

      网友评论

        本文标题:.NET SignalR Console Client demo

        本文链接:https://www.haomeiwen.com/subject/ijpgartx.html