如何使用SignalR加入群组

How to join a group using SignalR

本文关键字:何使用 SignalR      更新时间:2023-09-26

我刚开始使用SignalR(从今天开始),向所有连接的客户端发送消息很简单,但现在我只想发送到一个组。我找不到关于如何在客户端加入的简单文档。如果有人能帮忙,我怎么能简单地加入javascript方面的小组呢。谢谢你的帮助。

public class EventHub : Hub
{
    public void SendNewMedia(MediaInfoViewModel model,Guid eventId)
    {
        Clients.Group(eventId.ToString()).setupmedia(model);
    }
}
//Controller that is sending client new data
var eventHub = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
              var result = eventHub.Clients.Group(eventId.ToString()).setupmedia(eventViewer);
//Finally the javascript. Not sure how to setup just for a group
$(function () {
    var event = $.connection.eventHub;
    event.client.setupmedia = function (newMedia) {
        $('#photolist').prepend('<li><img src="' + newMedia.MediaUrl + '" class="img-polaroid span2"/></li>');
    };
    $.connection.hub.start(function() {
        event.server.create(eventID);//I know this is wrong but not sure how to connect
    }).done(function () {
        alert('conntected. Ready to retrieve data!');
    });
});

你不能。如果你可以从javascript加入一个群组,那么任何人都可以使用你的代码加入任何破坏安全的群组。如果确实需要这样做,请在服务器端创建一个方法,该方法以组名为参数,并将客户端添加到组中。

public void JoinGroup(string groupName)
{
    this.Groups.Add(this.Context.ConnectionId, groupName);
}

然后,像一样从JS调用它

eventHub.server.joinGroup("my-awsm-group");

-------------------------在Javascript(ReactJs)中------------------------------

const connection = new signalR.HubConnectionBuilder()
  .withUrl("connectionUrl")
  .build();
connection.start().then(res => {
    connection.invoke("JoinGroup", "groupName")  //JoinGroup is C# method name
        .catch(err => {
            console.log(err);
        });
}).catch(err => {
            console.log(err);
        });;

----------------在C#(.Net Core)------------------中

public class NotificationHub : Hub
    {
        public Task JoinGroup(string groupName)
        {
                return Groups.AddToGroupAsync(Context.ConnectionId, groupName);
        }
    } 

为了防止您现在遇到这个问题(就像我一样),这里有一个如何实现azure函数以支持组的示例。

https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-signalr-service#2x-c组管理输出样本