SignalR页面刷新可建立多个连接

Moh*_*vas 5 c# asp.net signalr

我想使用SignalR在客户端上显示一些实时随机数据。

问题是,每当我刷新页面时,它都会创建另一个连接并显示多个数据。

通常,我认为我的方法是错误的。

所以我做了。

步骤1:使用Nuget安装SignalR Install-Package Microsoft.AspNet.SignalR

步骤2:在Startup.cs文件中进行如下更改。

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        app.MapSignalR(); //Added this line for SignalR
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤3:创建集线器类。“ ServerStatisticsHub.cs”

public class ServerStatisticsHub : Hub
{
    public void ServerParameter()
    {
        Random r = new Random();
        int p = 0;
        int m = 0;
        int s = 0;

        while(true) //May be this is the foolish thing I'm doing
        {
            p = r.Next(0, 100);
            m = r.Next(0, 100);
            s = r.Next(0, 100);
            Clients.All.broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
            System.Threading.Thread.Sleep(2000);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤4:在主目录“ ServerState.cshtml”中创建一个视图。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>TestSignalR</title>
</head>
<body>
    <div id="serverProcessor"></div>
    <div id="serverMemory"></div>
    <div id="serverStorage"></div>

    <script src="@Url.Content("~/Scripts/jquery-2.2.3.min.js")"></script>    
    <script src="@Url.Content("~/Scripts/jquery.signalR-2.2.1.min.js")"></script>
    <script src="@Url.Content("~/signalr/hubs")"></script>
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var serverStatistics = $.connection.serverStatisticsHub;

            // Create a function that the hub can call back to display messages.
            serverStatistics.client.broadcastServerStatistics = function (serverStat) {
                var serverStatistic = JSON.parse(serverStat);
                console.log(serverStatistic);

                $('#serverProcessor').html(serverStatistic.processor + "%");
                $('#serverMemory').html(serverStatistic.memory + "%");
                $('#serverStorage').html(serverStatistic.storage + "%");
            };

            // Start the connection.
            $.connection.hub.start().done(function () {
                serverStatistics.server.serverParameter();
            });
        });

    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Moh*_*vas 2

我找到了解决此问题的解决方法。我不知道如何描述它。

在集线器类文件中完成以下代码更改。“服务器统计中心.cs”

Clients.Client(Context.ConnectionId).broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
Run Code Online (Sandbox Code Playgroud)

改变了

客户。全部。

Clients.Client(Context.ConnectionId).