如何从Blazor应用程序创建SignalR组

问题描述 投票:0回答:1

我有一个(服务器端)blazor应用程序,我想让用户填写一个小表格,然后按一个按钮来创建SignalR组,然后他们可以向其发送消息。

我有一个看起来像这样的Hub类:

public class RoomHub : Hub
{
    public async Task JoinRoomAsync(string groupName)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
    }

    public async Task LeaveRoomAsync(string groupName)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
    }

    public async Task BroadcastToRoomAsync(string groupName, string message)
    {
        await Clients.Group(groupName).SendAsync("OnMessage", message);
    }
}

以及从我的blazor组件中调用的Service类,它看起来像这样:

public class RoomService : IRoomService
{
    private ICosmosDbService _dbService;
    private RoomHub _roomHub;

    public RoomService(ICosmosDbService dbService, RoomHub roomHub)
    {
        this._dbService = dbService;
        this._roomHub = roomHub;
    }

    public async Task<Room> CreateRoom(string name)
    {
        Room r = new Room();
        r.Id = Guid.NewGuid().ToString();
        r.Name = name;
        await _dbService.AddItemAsync(r);
        await _roomHub.JoinRoomAsync(r.Name);

        return r;
    }

    public async Task SendToRoom(Room r, string message)
    {
        await _roomHub.BroadcastToRoomAsync(r.Name, message);
        return;
    }
}

[当我将RoomHub类添加到Startup.cs中的服务并运行我的应用程序时,当我按下按钮创建组时,它告诉我集线器的Context变量为空,并且失败。

我已经尝试过寻找其他方法来执行此操作,并得出结论,它与注入IHubContext<RoomHub>对象有关,但是此提供的对象似乎与我的Hub类根本无关。并且我不能用它直接创建组,因为我无权访问我需要的ConnectionId

我感觉Hub和HubContext之间存在我不了解的差距。从Blazor组件上的按钮按下开始,创建SignalR组的正确方法是什么?

.net-core signalr blazor-server-side asp.net-core-signalr
1个回答
0
投票

在访问集线器之前,需要使用HubConnectionHubConnectionBuilder建立并启动集线器连接。这需要包括您的集线器的url和从集线器接收的数据的处理程序方法。

首先在您的Service类中添加HubConnection字段。

private HubConnection _hubConnection;

根据您的服务生命周期和其他考虑,您可以在Service类构造函数中创建连接或使用它自己的方法。例如,我们将添加一个StartConnectionAsync任务。

    public async Task StartConnectionAsync()
    {
        // Create the connection
        _hubConnection = new HubConnectionBuilder()
            .WithUrl(_hubUrl) // _hubUrl is your base Url + Hub Url
            .Build();
        // Add Handler for when a client receives a broadcast message
        _hubConnection.On<string>("OnMessage", this.SomeEventHandler);
        // Then you start the connection
        await _hubConnection.StartAsync();
    }

不使用类型化的Hub,您将使用魔术字符串调用Hub方法。例如

await _hubConnection.SendAsync("JoinRoomAsync", groupName);

这应该使您入门。根据您上面发布的内容,我认为this github repo与您打算执行的操作类似。

© www.soinside.com 2019 - 2024. All rights reserved.