【问题标题】:mvc signalr how to display all connected usersmvc signalr 如何显示所有连接的用户
【发布时间】:2016-08-03 05:13:09
【问题描述】:

我需要使用信号器建立一个聊天,我是新来的。

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

在我的 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>
}

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

【问题讨论】:

  • this 可能会有所帮助
  • @user55 我读了这篇文章尝试过,但被卡住了。你能解释一下他在这行做了什么吗:chatEntities dc = new chatEntities();

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


【解决方案1】:

因此,您几乎要么只想将所有“活动”连接存储在某种数据库/存储或静态哈希集/字典中。

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

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

【讨论】:

  • C 它有帮助,但是 html 响应是我需要显示用户的连接,但它正在显示连接我如何返回用户安装?
  • 如何将用户映射到连接?我只看到你存储 ConnectionIds
  • 对不起,我今天才开始使用 signalr,我对此完全陌生,不知道你所说的映射连接是什么意思。基本上我需要的是显示活跃用户列表,顺便说一句,任何指向 Signalr 教程的链接都将不胜感激
  • SignalR 建立连接 ID。您可以选择以几种不同的方式将这些连接 ID 映射到用户。您如何将用户与连接相关联?字典/列表/数据库?
  • 我没有关联它们,但实际上我尝试将用户名和连接ID添加到数据库但我失败了,抱歉还在训练这个
猜你喜欢
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多