我想使用 SignalR 在客户端上显示一些实时随机数据。
Problem Is whenever I refresh the page it creates one more connection and shows multiple data.
主要是我认为我的方法是错误的。
所以我做了什么。
第 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
}
}
第 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 步:在主页“ServerState.cshtml”中创建一个 View 。
<!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>
最佳答案
我找到了解决此问题的解决方法。 不知道怎么形容。
在集线器类文件中完成以下代码更改。 “ServerStatisticsHub.cs”
Clients.Client(Context.ConnectionId).broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
改变了
Clients.All.
到
Clients.Client(Context.ConnectionId).
关于c# - SignalR 页面刷新建立多重连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43385834/