我正在尝试加入最新版SignalR的小组,显然它的行为与我能找到的答案不同。
这是我的中心地带
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);
}
}
这是我的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) });
});
});
}
我不确定要连接到X组的位置。
谢谢!
答案 0 :(得分:1)
通过遵循this tutorial
,我能够实现自己想要的目标简而言之:
创建一种处理组的方法:
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);
}
并在连接后调用该方法:
this.state.hubConnection.invoke("JoinGroup", this.state.groupName).catch(err => console.error(err));