您当前的位置: 首页 > 

寒冰屋

暂无认证

  • 2浏览

    0关注

    2286博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

寒冰屋 发布时间:2022-07-26 22:14:58 ,浏览量:2

目录

介绍

背景

Blazor代码

Windows窗体代码

结论

参考

介绍

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

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

背景

ASP.NET Core SignalR在Blazor 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");
           });

现在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("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("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
Home

  
    
    
    

注意:我在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("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("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桌面应用程序之间。

参考
  • 将ASP.NET Core SignalR与Blazor一起使用
  • Radzen组件

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

关注
打赏
1665926880
查看更多评论
立即登录/注册

微信扫码登录

0.0467s