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

目录

介绍

背景

Blazor代码

Windows窗体代码

结论

参考


介绍

我必须找到一种解决方案来解决旧的Windows窗体应用程序和基于WebBlazor应用程序之间的通信问题。

您可能想知道,为什么Windows窗体应该与Blazor通信?场景是:我有一个旧的Framework 2.0应用程序,然后它迁移到Framework 4.8,安装在使用Windows API但需要与Blazor应用程序交换数据的客户端上。

背景

ASP.NET Core SignalRBlazor App中实现非常简单,并且通信非常迅速。我建议您阅读Microsoft教程以了解这些功能。

Blazor代码

注意:下面,我有相同的微软教程步骤,如果你已经制作了教程,你可以使用它。

首先,我们需要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中心的终结点:

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页面启动时触发的Blazor后端代码OnInitializedAsync()

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>

注意:我在Razor页面中使用了Radzen组件。如果您有兴趣,请看这里

现在测试应用程序,当应用程序启动时,将url复制到另一个浏览器中,如果一切正常,当您从应用程序发送消息时,您将看到另一个,反之亦然。

Windows窗体代码

现在我们构建了一个Windows窗体应用程序,客户端使用它来发送和接收来自本地Blazor应用程序的消息。

打开Visual Studio并创建一个新的Windows窗体框架4.8应用程序。

NuGet安装包含ASP.NET Core SignalR客户端的Microsoft.AspNetCore.SignalR.Client包。

我们需要执行相同的Blazor客户端实现,因此创建初始化方法并从加载表单中调用它。

async Task InizializzaConnectioTuBlazorHub()
{
    hubConnection = new HubConnectionBuilder()
   .WithUrl("http://localhost:5000/chathub")
   .Build();

    hubConnection.On<string>("ReceiveMessage", (message) =>
    {
        _messageRecived = message;
        textBox1.Text= _messageRecived;
    });

    await hubConnection.StartAsync();
}

注意本地应用程序URL“http://localhost: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("http://localhost: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桌面应用程序之间。

参考

https://www.codeproject.com/Tips/5327741/Blazor-Communicates-with-Win-Desktop-App-through-S

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值