Reputation: 9408
I am new to using SignalR (started today), Pretty simple to send a message to ALL clients connected, but now I want to just send to a group. I cannot find simple documentation on how to join on the client side. If anyone can help, how can I SIMPLY join a group on the javascript side. Thanks for any help.
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!');
});
});
Upvotes: 26
Views: 42806
Reputation: 582
-------------------------In 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);
});;
----------------In C# (.Net Core)-----------------
public class NotificationHub : Hub
{
public Task JoinGroup(string groupName)
{
return Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}
}
Upvotes: 15
Reputation: 2674
Just in case you come across this question now (like I did), here is an example for how to implement an azure function to support groups.
Upvotes: 2
Reputation: 6237
You can't. If you could join a group from javascript then anyone may use your code to join any group which breaks security. If you really need to do that - create a method on the server side that takes a group name as parameter and adds the client to the group.
public void JoinGroup(string groupName)
{
this.Groups.Add(this.Context.ConnectionId, groupName);
}
Afterwards, call it from JS like that
eventHub.server.joinGroup("my-awsm-group");
Upvotes: 44