Blazor 通过 SignalR 与 Win 桌面应用程序通信





5.00/5 (11投票s)
Blazor 和 Windows Form 桌面应用程序
引言
我需要找到一个解决方案来解决旧 Windows Form 应用程序和基于 Blazor 的 Web 应用程序之间的通信问题。
你可能想知道,为什么 Windows Form 要与 Blazor 通信?场景是:我有一个旧的 Framework 2.0 应用程序,然后迁移到 Framework 4.8,安装在客户端上,它使用 Windows API,但需要与 Blazor 应用程序交换数据。
背景
ASP.NET Core SignalR 在 Blazor 应用程序中实现非常简单,通信速度非常快。我建议你阅读 Microsoft 的教程以了解其功能。
Blazor 代码
注意:以下是我与 Microsoft 教程相同的步骤,如果你已经完成了该教程,则可以使用它。
首先,我们需要 Visual Studio 2022 并创建一个 Blazor 服务器应用程序 .NET 6.0。在应用程序内部,创建一个名为 Hubs 的文件夹,然后创建一个名为 ChatHub
的类。
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace RadzenBlazorSignalR.Hubs
{
public class ChatHub : Hub //NB: inherits from Hub
{
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
}
}
在 Program.cs 中,映射 Blazor hub 的端点
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
});
现在 hub 已经准备就绪,但应用程序需要发送和接收一些消息,因此我们需要实现客户端。
为此,首先添加 Microsoft.AspNetCore.SignalR.Client
包,然后创建一个方法来初始化连接。
HubConnection hubConnection;
string _messageRecived { get; set; }
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(MyUriHelper.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string>("ReceiveMessage", (message) =>
{
_messageRecived = message;
StateHasChanged();
});
await hubConnection.StartAsync();
}
在上面的代码中,我使用了 Blazor 的后端代码 OnInitializedAsync()
,该代码在启动 Blazor 页面时触发。
HubConnectionBuilder()
从 ToAbsoluteUri()
和 hub 的名称 chathub
构建本地 Blazor 应用程序的 Uri。
hubConnection.On<>
映射 ReceiveMessage
事件,该事件在调用 SendMessage()
方法时触发。
现在准备一个发送消息的方法,你可以从 Blazor 页面的按钮中调用它。
public async Task Send()
{
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendMessage", _messageToSend);
}
}
以下是完整的 Blazor 页面后端代码。
public partial class HomeComponent
{
[Inject]
protected NavigationManager MyUriHelper { get; set; }//to get current Uri
public string _messageToSend { get; set; }//to bind on textbox
public string _messageRecived { get; set; }//to bind on a label or so...
private HubConnection hubConnection;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(MyUriHelper.ToAbsoluteUri("/chathub"))
.Build();
//receive event
hubConnection.On<string>("ReceiveMessage", (message) =>
{
_messageRecived = message;
StateHasChanged();
});
await hubConnection.StartAsync();
}
//send message
//call Send method from button click
public async Task Send()
{
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendMessage", _messageToSend);
}
}
}
@page "/"
@page "/home"
@layout MainLayout
@inherits RadzenBlazorSignalR.Pages.HomeComponent
@using Radzen
@using Radzen.Blazor
<PageTitle>Home</PageTitle>
<RadzenContent Container="main">
<ChildContent>
<RadzenHeading Size="H1" Text="Home">
</RadzenHeading>
<div class="row">
<div class="col-md-3">
<RadzenTextBox @bind-Value="@(_messageToSend)" Name="Textbox0">
</RadzenTextBox>
</div>
<div class="col-md-3">
<RadzenButton Text="Invia" Click="@Button0Click">
</RadzenButton>
</div>
<div class="col-md-4">
<RadzenLabel Text="@($"{(_messageRecived)}")">
</RadzenLabel>
</div>
</div>
</ChildContent>
</RadzenContent>
注意:我使用了 Radzen 组件在 Razor 页面中。如果你感兴趣,请查看 这里。
现在测试应用程序,当应用程序启动时,将 url 复制到另一个浏览器中,如果一切正常,当你从一个应用程序发送消息时,你将在另一个应用程序中看到,反之亦然。
Windows Form 代码
现在我们构建一个 Windows Form 应用程序,供客户端用于向本地 Blazor 应用程序发送和接收消息。
打开 Visual Studio 并创建一个新的 Windows Form framework 4.8 应用程序。
从 NuGet 安装 Microsoft.AspNetCore.SignalR.Client
包,其中包含 ASP.NET Core SignalR 的客户端。
我们需要执行与 Blazor 客户端相同的实现,因此创建初始化方法并在加载表单时调用它。
async Task InizializzaConnectioTuBlazorHub()
{
hubConnection = new HubConnectionBuilder()
.WithUrl("https://:5000/chathub")
.Build();
hubConnection.On<string>("ReceiveMessage", (message) =>
{
_messageRecived = message;
textBox1.Text= _messageRecived;
});
await hubConnection.StartAsync();
}
请注意本地应用程序 Url "https://:5000/chathub"。
准备 Send
方法并从单击按钮事件中调用它。
async Task InviaAsync()
{
if (hubConnection != null)
{
await hubConnection.SendAsync("SendMessage", "Desktop: Ciao");
}
}
以下是完整的代码
private void Form1_Load(object sender, EventArgs e)
{
InizializzaConnectioTuBlazorHub();
}
private void button1_Click(object sender, EventArgs e)
{
Send();
}
HubConnection hubConnection;
string _messageRecived;
async Task InizializzaConnectioTuBlazorHub()
{
hubConnection = new HubConnectionBuilder()
.WithUrl("https://:5000/chathub")
.Build();
hubConnection.On<string>("ReceiveMessage", (message) =>
{
_messageRecived = message;
textBox1.Text= _messageRecived;
});
await hubConnection.StartAsync();
}
async Task Send()
{
if (hubConnection != null)
{
await hubConnection.SendAsync("SendMessage", "Desktop: Bye!");
}
}
就是这样!
如果你启动 Blazor 应用程序和 Windows 应用程序,你可以从所有应用程序发送和接收消息。
结论
在这个例子中,我们看到了使用 SignalR 进行通信是多么容易,不仅在 Blazor 应用程序之间,而且与 Windows 桌面应用程序之间。
参考文献
历史
- 2022 年 3 月 17 日:初始版本