mvc signalr如何显示所有连接的用户

时间:2016-08-02 10:10:08

标签: asp.net-mvc signalr signalr-hub

我需要使用signalr建立聊天,我是新手。

到目前为止,我只通过阅读其他代码和教程来获得聊天,这就是我得到的:

在我的ChatApp.Hubs上我得到了以下代码

public static class UserHandler
{
    public static HashSet<string> ConnectedIds = new HashSet<string>();
}
public class ChatHub : Hub
{

    public void Send(string name, string message)
    {
        // Call the addNewMessageToPage method to update clients.
        Clients.All.addNewMessageToPage(name, message);
    }

    public override Task OnConnected()
    {
        UserHandler.ConnectedIds.Add(Context.ConnectionId);
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        UserHandler.ConnectedIds.Remove(Context.ConnectionId);
        return base.OnDisconnected(stopCalled);
    }
}

我的观点是从教程中复制过来的

@{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion">
    </ul>
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.--> 
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.  
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + htmlEncode(name) 
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

我现在需要的是在视图中显示所有连接的用户
恭喜你的帮助 提前致谢

1 个答案:

答案 0 :(得分:4)

所以,你几乎要么只想存储所有&#39; Active&#39;某种数据库/存储或静态哈希集/字典中的连接。

您在用户连接时保存ConnectionIds,并在断开连接时将其删除:

集线器

public class ChatHub : Hub
{
   static HashSet<string> CurrentConnections = new HashSet<string>();

    public override Task OnConnected()
    {
        var id = Context.ConnectionId;
        CurrentConnections.Add(id);

        return base.OnConnected();
    }

    public override System.Threading.Tasks.Task OnDisconnected()
    {
        var connection = CurrentConnections.FirstOrDefault(x => x == Context.ConnectionId);

        if (connection != null)
        {
            CurrentConnections.Remove(connection);
        }

        return base.OnDisconnected();
    }


    //return list of all active connections
    public List<string> GetAllActiveConnections()
    {
        return CurrentConnections.ToList();
    }

}

客户端

我添加了一个按钮和一个无序列表。

HTML

&#13;
&#13;
<button id="show-all-connections">Show Connections</button>
<ul id="user-list">
</ul>
&#13;
&#13;
&#13;

并添加了这个javascript(使用jQuery)

    $("#show-all-connections").on("click", function () {

        debugger;

        chatHub.server.getAllActiveConnections().done(function (connections) {
            $.map(connections, function (item) {
                $("#user-list").append("<li>Connection ID : " + item + "</li>");
            });
        });
    });

希望这有帮助。

更新

在您的方案中,我没有看到使用自定义UserId提供程序或任何内容的任何钩子,因此您将不得不向用户询问用户名并使用该名称保存连接ID。

HTML

的JavaScript

        $("#add-connection").click(function () {
            var name = $("#user-name").val();
            if (name.length > 0) {
                chatHub.server.connect(name);
            }
            else {
                alert("Please enter your user name");
            }
        });

集线器

    static List<Users> SignalRUsers = new List<Users>();

    public void Connect(string userName)
    {
        var id = Context.ConnectionId;

        if (SignalRUsers .Count(x => x.ConnectionId == id) == 0)
        {
            SignalRUsers .Add(new Users{ ConnectionId = id, UserName = userName });
        }
    }

    public override System.Threading.Tasks.Task OnDisconnected()
    {
        var item = SignalRUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
        if (item != null)
        {
            SignalRUsers.Remove(item);
        }

        return base.OnDisconnected();
    }

Users.cs

public class Users
{
    public string ConnectionId { get; set; }
    public string UserName { get; set; }
}

这是伪代码,因为我目前无法运行此代码。希望它有所帮助,并给你一个明确的方向。