1

I am doing my first tests with SignalR. I am toying with chat messages, but that's only a first step to replace all the polling from client to server which I have today on my site.

I have a lot of scenarios where I want to notify certain users either by their login or by their ID. The idea is that I am adding each user to two groups as soon as he connects. I do this in OnConnected and that event is called.

When I send a chat message, I have two modes: either public or personal. If it is personal the sender is notified and the recipient should be notified. The sender gets a message but the group never does. It seems to be impossible to found out how many members a group has.

Any ideas what's going wrong here?

public class GlobalHub:Hub
{
    private Users user;

    private void AuthenticateUser()
    {
        var ydc = new MyDataContext();
        user = ydc.Users.First(u => u.Login == HttpContext.Current.User.Identity.Name);
    }

    public override Task OnConnected()
    {
        var ydc = new MyDataContext();
        user = ydc.Users.First(u => u.Login == HttpContext.Current.User.Identity.Name);

        Groups.Add(Context.ConnectionId, user.Login);
        Groups.Add(Context.ConnectionId, user.ID.ToString());
        return base.OnConnected();
    }


public void SendChatMessage(string message, string recipient)
{
    AuthenticateUser();
    var cm = ChatController.AddChatMessage(user.Login, user.ID, recipient, tmessage);

    if (recipient != "")
    {
        Clients.Caller.NewMessage(cm);
        Clients.Group(recipient).NewMessage(cm);
    }
    else
    {
        Clients.All.NewMessage(cm);
    } 
}
}
4

1 回答 1

1

看起来 Groups.Add 并没有立即加入到组的连接,而是返回一个需要启动的任务。尝试返回 Groups.Add 的结果作为 OnConnectedMethod 的结果。

另见更详细的解释:https ://stackoverflow.com/a/15469038/174638

于 2013-03-18T00:22:20.660 回答