asp.net-mvc - mvc signalr如何显示所有连接的用户

标签 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>
}

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

最佳答案

因此,您很可能只想将所有“事件”连接存储在某种数据库/存储或静态哈希集/字典中。

您在用户连接时保存 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 或任何东西的任何 Hook ,因此您将不得不向用户询问用户名并保存连接 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();
    }

用户.cs

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

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

关于asp.net-mvc - mvc signalr如何显示所有连接的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38717559/

相关文章:

c# - 在 Signalr .net 核心中——应该在哪里进行验证?

SignalR - 找不到类型或命名空间名称 'Hub'

asp.net-mvc - MVC Controller 与开箱即用的 Sitecore Controller

c# - 如何获取 ASP.NET 应用程序路径?

.net - ASP.NET MVC Html.ActionLink 结果 URL - 编码方式

wcf - 具有 WCF 服务的 SignalR 自托管和客户端将是桌面用户

c# - SignalR - 客户端需要 ASP.net?

c# - 向空的 ASP.NET SignalR 组广播会浪费资源吗?

c# - 使用 SignalR 和 IProgress 接口(interface)的进度报告

html - 如何在 MVC 3 Razor 中使用文本标签