在.Net Framework平台下WPF实现SignalR客户端
1、新建.Net Framework平台下WPF应用程序
Nuget包安装 Microsoft.AspNetCore.SignalR.Client
<Window x:Class="WpfFramework.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfFramework" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="40"/> <RowDefinition Height="*"/> <RowDefinition Height="50"/> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> <Label Content="地址"/> <TextBox x:Name="txtUrl" Width="300"/> <Button x:Name="connectBtn" Height="35" Width="100" Content="连接" Click="connectBtn_Click"/> </StackPanel> <Grid Grid.Row="1"> <ListView Name="msgList"> </ListView> </Grid> <StackPanel Orientation="Horizontal" Grid.Row="2" VerticalAlignment="Center"> <TextBox Height="30" Width="300" Name="txtSend"> </TextBox> <Button Content="发送" Name="SendBtn" Width="100" Click="SendBtn_Click"></Button> </StackPanel> </Grid> </Window>
public partial class MainWindow : Window { private HubConnection _connection; public MainWindow() { InitializeComponent(); txtUrl.Text = @"http://127.0.0.1:5000/myTestHub"; } private async void connectBtn_Click(object sender, RoutedEventArgs e) { _connection = new HubConnectionBuilder() .WithUrl(txtUrl.Text) .Build(); _connection.On<string, string>("myMessage", (s1, s2) => OnSend(s1, s2)); _connection.Closed += _connection_Closed; await _connection.StartAsync(); connectBtn.IsEnabled = false; } private Task _connection_Closed(Exception arg) { return Task.Run(() => { Dispatcher.BeginInvoke(new Action(() => { connectBtn.IsEnabled = true; } )); }); } private void OnSend(string name, string message) { msgList.Items.Add("用户名称:" + name+ " 消息内容:" + message); } private async void SendBtn_Click(object sender, RoutedEventArgs e) { await _connection.InvokeAsync("Send", "WPFApp", txtSend.Text); } }
2、服务端还是调用之前文章中的SignalR服务端