2017-04-13 188 views
4

我想在使用SignalR的客户端上显示一些实时随机数据。SignalR页面刷新使多重连接

问题无论何时刷新页面,它都会创建一个连接 并显示多个数据。

大多数情况下,我认为我的方法是错误的。

所以我做了什么。

步骤1:安装SignalR

步骤2使用的NuGet Install-Package Microsoft.AspNet.SignalR:在Startup.cs文件所做的更改如下。

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

第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); 
     } 
    } 
} 

第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> 

回答

2

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

在Hub类文件中完成以下代码更改。 “ServerStatisticsHub.cs”

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

改变

Clients.All。

Clients.Client(Context.ConnectionId)。

+1

我真的不会说它是一种解决方法,这实际上是一个可能适当的解决方案。您的问题是由于您在客户端连接时调用包含无限循环的函数所致。所以客户端1连接 - >启动无限循环。客户端2连接 - >无限循环再次启动。他们在不同的线程上运行,因此再次启动它并不会杀死前一个线程。由于您不会以任何方式退出循环,因此每个新客户端都会导致启动一个新的无限循环,每个循环都会向每个其他客户端广播消息。 –

+0

那么有没有什么解决方案可以在页面重新加载时关闭无限循环? –

+0

就我个人而言,我不会为每个新客户启动一个无限循环。为什么我说你做了什么可能是一个可能的解决方案,因为它可能是,在这种情况下,消息不需要被广播到所有连接的客户端。 –