Reputation: 612
I want to show some live random data on client using SignalR.
Problem Is whenever I refresh the page it creates one more connection and shows multiple data.
Mostly I think my approach is wrong.
So what I have done.
Step 1: Installed SignalR Using Nuget Install-Package Microsoft.AspNet.SignalR
Step 2: Made changes in Startup.cs File as follows.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR(); //Added this line for SignalR
}
}
Step 3: Created Hub Class. "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);
}
}
}
Step 4: Created an View in 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>
Upvotes: 6
Views: 2027
Reputation: 612
I found a workaround to fix this issue. I don't know how to describe it.
The following code change done in Hub Class file. "ServerStatisticsHub.cs"
Clients.Client(Context.ConnectionId).broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
Changed
Clients.All.
to
Clients.Client(Context.ConnectionId).
Upvotes: 2