Reputation: 627
I'm trying to join a group on the latest SignalR version and apparently it behaves different from the responses I could find.
Here's my hub:
public class NotificationsController : Hub
{
public void Messages(string groupName, string message)
{
//I don't get this one
Clients.Group(groupName).SendAsync("Messages", $"from the group : {message}");
// this one is fine
Clients.All.SendAsync("Messages", message);
}
}
And here's my JS:
handleConnect(event) {
const hubConnection = new HubConnectionBuilder()
.withUrl("/notifications")
.configureLogging(LogLevel.Information)
.build();
this.setState({ hubConnection, isConnected: true }, () => {
this.state.hubConnection
.start()
.then(function() {
console.log('Connection started!');
})
.catch(err => console.log('Error while establishing connection :('));
this.state.hubConnection.on("Messages", (message) => {
this.setState({ messages: this.state.messages.concat(message) });
});
});
}
I'm not sure where to stick that I want to connect to the group X.
Thanks!
Upvotes: 1
Views: 1337
Reputation: 627
I was able to achieve what I wanted by following this tutorial
in short:
Create a method to handle the groups:
public async Task JoinGroup(string group)
{
if (connectionsNgroup.ContainsKey(Context.ConnectionId))
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, connectionsNgroup[Context.ConnectionId]);
connectionsNgroup.Remove(Context.ConnectionId);
}
connectionsNgroup.Add(Context.ConnectionId, group);
await Groups.AddToGroupAsync(Context.ConnectionId, group);
}
and invoke the method after connecting:
this.state.hubConnection.invoke("JoinGroup", this.state.groupName).catch(err => console.error(err));
Upvotes: 1