SignalR中的匿名私聊

时间:2014-04-08 13:13:21

标签: c# .net signalr

我对SignalR有点新鲜。我在一定程度上了解集线器,但我不明白两个用户如何在排除其他用户的情况下共享连接。

我的情况是,我希望未经身份验证的公共网站用户能够与客户服务用户发起私人(不一定是安全的)聊天会话。

是否有一个例子或资源让我指出了正确的方向?

我查看了一些资源,包括http://www.asp.net/signalr/overview/signalr-20/hubs-api/mapping-users-to-connections但尚未找到正确的方案。

3 个答案:

答案 0 :(得分:4)

您可以创建组,因此向您的集线器添加一些方法(订阅方法应返回任务,因为它们是异步的......)

public Task SubscribeToGroup(string groupName)
{
     return Groups.Add(Context.ConnectionId, groupName);
}

然后您可以正常向该组的用户发布通知,但是通过群集...

public void BroadcastMessageToGroup(string groupName, string message)
{
    Clients.Group(groupName).onCaptionReceived(message);
}

现在只有该特定群组的订阅者才能收到该消息!

希望这有帮助。

您可以在此处找到SignalR Groups的教程。

http://www.asp.net/signalr/overview/signalr-20/hubs-api/working-with-groups

答案 1 :(得分:2)

您可以在Hub的API中创建一个组,在此方法中,每个用户都是该组的成员。他们向该组发送消息(通过服务器),因为他们只有2名成员,他们是唯一看到消息的人(私有)

答案 2 :(得分:1)

您还可以通过连接ID直接向群组成员发送消息。这需要您的应用在连接和断开连接时跟踪用户的连接ID,但这并不困难:

//Users: stores connection ID and user name
public static ConcurrentDictionary Users = new ConcurrentDictionary();

public override System.Threading.Tasks.Task OnConnected()
{
    //Add user to Users; user will supply their name later. Also give them the list of users already connected
    Users.TryAdd(Context.ConnectionId, "New User");
    SendUserList();
    return base.OnConnected();
}

//Send everyone the list of users (don't send the userids to the clients)
public void SendUserList()
{
    Clients.All.UpdateUserList(Users.Values);
}

//Clients will call this when their user name is known. The server will then update all the other clients
public void GiveUserName(string name)
{
    Users.AddOrUpdate(Context.ConnectionId, name, (key, oldvalue) => name);
    SendUserList();
}

//Let people know when you leave (not necessarily immediate if they just close the browser)
public override System.Threading.Tasks.Task OnDisconnected()
{
    string user;
    Users.TryRemove(Context.ConnectionId, out user);
    SendUserList();
    return base.OnDisconnected();
}

//Ok, now we can finally send to one user by username
public void SendToUser(string from, string to, string message)
{
    //Send to every match in the dictionary, so users with multiple connections and the same name receive the message in all browsers
    foreach(KeyValuePair user in Users)
    {
        if (user.Value.Equals(to))
        {
            Clients.Client(user.Key).sendMessage(from, message);
        }
    }
}
相关问题