javascript 如何在 SignalR 上获取已连接客户端的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12660313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:48:11  来源:igfitidea点击:

How to get a list of connected clients on SignalR

javascriptc#.netasp.net-mvcsignalr

提问by Crime Master Gogo

I am quite new to SignalR. My first assignment is to make simple chat app.

我对 SignalR 很陌生。我的第一个任务是制作简单的聊天应用程序。

I have been browsing and reading and finally made a page where you come and chat and it works fine.

我一直在浏览和阅读,最后制作了一个页面,您可以在这里聊天,并且效果很好。

Now I need to show a list of connected clients. To achieve this I have wrote the following code. This is my HUB.

现在我需要显示已连接客户端的列表。为了实现这一点,我编写了以下代码。这是我的 HUB。

public class ChatHub: Hub
{

    chatEntities dc = new chatEntities();
    public void Send(string message,string clientName)
    {
        Clients.addMessage(message,clientName);

    }

    // I want to save the user into my database, when they join 
    public void Joined(string userId,string userName)
    {

        CurrentChattingUsers cu = new CurrentChattingUsers();
        cu.ConnectionId = userId;
        cu.UserName = userName;

        dc.CurrentChattingUsers.AddObject(cu);
        dc.SaveChanges();


       Clients.joins(userId, userName);
    }

    // This will return a list of connected user from my db table.
    public List<ClientModel> GetConnectedUsers()
    {
        var query = (from k in dc.CurrentChattingUsers
                     select new ClientModel()
                     {
                         FullName = k.UserName,
                         UserId = k.ConnectionId
                     }).ToList();
        return query;
    }   


}

And thats it...Now what?? Am I going to the right direction? If, I am then how to call this methods from the view? Some good suggestions will really help me out. cheers

就是这样......现在呢??我会朝着正确的方向前进吗?如果,我又如何从视图中调用此方法?一些好的建议会真正帮助我。干杯

EDIT:

编辑:

I have added the following script when the hub start

我在集线器启动时添加了以下脚本

$.connection.hub.start(function () {
            chat.getConnectedUsers();

        });

This is the method that returns the client names in my Hub

这是在我的集线器中返回客户端名称的方法

  public List<ClientModel> GetConnectedUsers()
    {
        var data = (from k in dc.Users
                     select new ClientModel()
                     {
                         FullName = k.UserName

                     }).ToList();

         Clients.loadUsers(data);
        return data;
    }

in firebug i can see it returns something as follows;

在萤火虫中,我可以看到它返回如下内容;

{"State":{},"Result":[{"FullName":"mokarom","UserId":null},  {"FullName":"aka8000","UserId":null},{"FullName":"johnnyno5","UserId":null},{"FullName":"reza","UserId":null},{"FullName":"amyo","UserId":null},{"FullName":"rezatech","UserId":null}],"Id":"0","Error":null,"StackTrace":null}

But, how would I display that in my view??

但是,我将如何在我的视图中显示它?

EDIT:

编辑:

this the complete view so far

这是迄今为止的完整视图

<script type="text/javascript">
    var chat;
    var myClientName
    $(document).ready(function(){

      myClientName = '@Request.Cookies["ChatterName"].Value';


        // Created proxy
        chat = $.connection.chatHub;
        // Assign a function to be called by the server
        chat.addMessage = onAddMessage;

        // Register a function with the button click
        $("#broadcast").click(onBroadcast);


        $('#message').keydown(function (e) {
            if (e.which == 13) { //Enter
                e.preventDefault();

                onBroadcast();

            }
        });

        // Start the connection
        $.connection.hub.start(function () {
           chat.getConnectedUsers();

        });

        chat.loadUsers = function (data) {
            loadUsers(data); 

         };
    });


    function onAddMessage(message,clientName) {
        // Add the message to the list
        $('#messages').append('<div class="chatterName">' + clientName + ' </div><div class="chatterMessage"> ' + message + '</div><div class="clear">');

    }
    function onBroadcast() {
        // Call the chat method on the server
        chat.send($('#message').val(), myClientName);
        $('#message').val('');
    }
    function loadUsers(data) {
        $('#clientList').html(data.Result[0].FullName);

    }
</script>

Problem: don't see anything here: $('#clientList').html(data.Result[0].FullName); firebug says 'data is not defined'

问题:这里什么也没看到:$('#clientList').html(data.Result[0].FullName); 萤火虫说“数据未定义”

采纳答案by dove

JavaScript

JavaScript

var chats = $.connection.chatHub;
chats.loadUsers = function (data) { loadUsers(data); };
var connectedUserCount = 0;

$.connection.hub.start(function () 
         { chats.getConnectedUsers(); });

function loadUsers =  = function (data) {
  console.log(data); //so you can see your data in firebug.etc
            //which signal r will have converted to json so you could try
  var numberOfUsers = data.length;  
}

Once hub is started chats would have all the public functions of your hub available as javascript functions. This is what the signalr/hubs creates using the best available connection method between client and server.

一旦集线器启动,聊天将把集线器的所有公共功能都作为 javascript 函数使用。这是信号器/集线器使用客户端和服务器之间的最佳可用连接方法创建的内容。

In reverse your C# hub will have access to any javascripts functions you setup, e.g.

反过来,您的 C# 集线器将可以访问您设置的任何 javascripts 函数,例如

Clients.loadUsers(query);  
//add this to you server side just before you return query

ps - you might also consider using OnConnectedAsync, though of course you might still persist these. I'm also waiting for full support for web farm support using sql, which is in the pipeline.

ps - 你也可以考虑使用OnConnectedAsync,当然你可能仍然坚持这些。我也在等待对使用 sql 的 Web 场支持的全面支持,该支持正在筹备中