SignalR and Joining Groups

为君一笑 提交于 2019-12-04 05:14:11
testpattern

I've had pretty much the same experience as you and have sort of worked/battled my way through it, so I'll share what I've done.

You'll need to capture a state somewhere. Check out the SignalR Hubs wiki https://github.com/SignalR/SignalR/wiki/Hubs under Roundtripping from Client to Server. I found that useful as it tells you how to set state on the server hub or client and retrieve it at the other end.

I came to same conclusion as you, that the Join is manually triggered by some event. I'm using a poll to see if anyone has requested a chat with the user. You can actually push from the server (see SignalR Join Group From Controller), meaning that the controller action that handles adding a new chat message can call the hub's Join method:

// join chatroom
public Task Join(dynamic mygroup)
{
var groupName = groupy.GetGroupName(parent.userId, (int)mygroup.userIdTo);
return Groups.Add(Context.ConnectionId, groupName);
}

For my group names, I use a Singleton to generate and keep track of names using a Dictionary<string, int[]> (the int[] is for userIds).

For the client state stuff, I ended up making a custom JavaScript object that managed the group name, like this...

Chat.Chatgroup = function (groupId, userIdTo) {
this.GroupId = groupId; // our group's title / id
this.UserIdTo = userIdTo; // who the other user is
}

Then I call the signalR method after connecting

onechat.getOurGroup(mygroup) // invoke method on server
.done(function (response) {
mygroup = response;
 /* + whatever else you need to do*/ });

Now you can set a state on the server and hold that state on the client:

public dynamic GetOurGroup(dynamic mygroup)
{
var ourId = groupy.GetGroupName(parent.userId, (int)mygroup.UserIdTo);
mygroup.GroupId = ourId;                    
return mygroup;
}

Hope it's at least vaguely helpful!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!