我想使用SignalR在客户端上显示一些实时随机数据.
Problem Is whenever I refresh the page it creates one more connection
and shows multiple data.
大多数情况下,我认为我的方法是错的.
所以我做了什么.
步骤1:使用Nuget Install-Package Microsoft.AspNet.SignalR安装SignalR
第2步:在Startup.cs文件中进行如下更改.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR(); //Added this line for SignalR
}
}
第3步:创建Hub类. “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步:在Home“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>
最佳答案 我找到了解决此问题的解决方法.
我不知道如何描述它.
在Hub类文件中完成以下代码更改. “ServerStatisticsHub.cs”
Clients.Client(Context.ConnectionId).broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
变
Clients.All.
至
Clients.Client(Context.ConnectionId).