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

mvc signalr how to display all connected users

我需要使用 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>
}

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

因此,您几乎只想将所有 'Active' 连接存储在某种 database/storage 或静态 hashset/dictionary.

您在用户连接时保存 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

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

并添加了这个 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 Provider 或任何东西的挂钩,所以你将不得不向用户询问用户名并用它保存连接 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; }
}

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