安装 SignalR .NET client Nuget 包
Install-Package Microsoft.AspNetCore.SignalR.Client
连接SignalR Hub
使用 HubConnectionBuilder
类并调用 Build
方法与Signal R Hub 建立连接。在建立连接的同时,可以配置请求Header,Log level,协议类型(protocol),传输类型(transport type),等其它选项。
设置好连接后使用StartAsync启动连接。
using System; using System.Threading.Tasks; using System.Windows; using Microsoft.AspNetCore.SignalR.Client; namespace SignalRChatClient { public partial class MainWindow : Window { HubConnection connection; public MainWindow() { InitializeComponent(); connection = new HubConnectionBuilder() .WithUrl("http://localhost:53353/ChatHub") .Build(); connection.Closed += async (error) => { await Task.Delay(new Random().Next(0,5) * 1000); await connection.StartAsync(); }; } private async void connectButton_Click(object sender, RoutedEventArgs e) { connection.On<string, string>("ReceiveMessage", (user, message) => { this.Dispatcher.Invoke(() => { var newMessage = $"{user}: {message}"; messagesList.Items.Add(newMessage); }); }); try { await connection.StartAsync(); messagesList.Items.Add("Connection started"); connectButton.IsEnabled = false; sendButton.IsEnabled = true; } catch (Exception ex) { messagesList.Items.Add(ex.Message); } } private async void sendButton_Click(object sender, RoutedEventArgs e) { try { await connection.InvokeAsync("SendMessage", userTextBox.Text, messageTextBox.Text); } catch (Exception ex) { messagesList.Items.Add(ex.Message); } } } }
连接中断异常处理
自动重新连接
连接中断后自动重新连接,可以通过配置直接完成。
HubConnection connection= new HubConnectionBuilder()
.WithUrl(new Uri(“http://127.0.0.1:5000/chatHub”))
.WithAutomaticReconnect()
.Build();
还可以在WithAutomaticReconnect()中配置等待重新连接的时间秒数。
通过自定义HubConnectionState.Reconnecting事件可以自定义处理每次重新连接时要执行的操作。
connection.Reconnecting += error =>
{
Debug.Assert(connection.State == HubConnectionState.Reconnecting);
// Notify users the connection was lost and the client is reconnecting.
// Start queuing or dropping messages.
return Task.CompletedTask;
};
类似的,还有自定义的 Connected
事件方法。
connection.Reconnected += connectionId =>
{
Debug.Assert(connection.State == HubConnectionState.Connected);
// Notify users the connection was reestablished.
// Start dequeuing messages queued while reconnecting if any.
return Task.CompletedTask;
};
WithAutomaticReconnect() 只能处理连接后的中断连接的重新连接行为,不能处理首次连接失败的情况。首次连接的失败处理需要采用以下方式。
public static async Task<bool> ConnectWithRetryAsync(HubConnection connection, CancellationToken token)
{
// Keep trying to until we can start or the token is canceled.
while (true)
{
try
{
await connection.StartAsync(token);
Debug.Assert(connection.State == HubConnectionState.Connected);
return true;
}
catch when (token.IsCancellationRequested)
{
return false;
}
catch
{
// Failed to connect, trying again in 5000 ms.
Debug.Assert(connection.State == HubConnectionState.Disconnected);
await Task.Delay(5000);
}
}
}
自动重连接,执行4次后如果仍然失败,就会触发connection.Closed += error =>的事件。
connection.Closed += error =>
{
Debug.Assert(connection.State == HubConnectionState.Disconnected);
// Notify users the connection has been closed or manually try to restart the connection.
return Task.CompletedTask;
};
重连接的等待时间也可以分别设置不同时长。
HubConnection connection= new HubConnectionBuilder()
.WithUrl(new Uri(“http://127.0.0.1:5000/chatHub”))
.WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(10) })
.Build();
// .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) yields the default behavior.
手动重连接
手动重连接是通过connection.Closed事件的自定义处理的。可以自由的设置等待时长。
connection.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0,5) * 1000);
await connection.StartAsync();
};
调用Signal R Hub 方法
await connection.InvokeAsync(“SendMessage”, userTextBox.Text, messageTextBox.Text);
从Signal R Hub 调用 client 方法
connection.On<string, string>(“ReceiveMessage”, (user, message) => { this.Dispatcher.Invoke(() => { var newMessage = $”{user}: {message}“; messagesList.Items.Add(newMessage); }); });
这个方法实际执行是通过SendMessage方法执行的。
公众号近期文章
0 Responses to “详解 ASP.NET Core SignalR .NET Client 的使用”