SignalR的简单实现

时间:2023-12-12 21:10:02

1创建mvc的空项目

2添加文件夹Counters放在里面的类用于封装性能计数器

3创建PerfCounterWrapper类用于封装性能计数器的实体

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web; namespace SignalR.Counters
{
public class PerfCounterWrapper
{
public PerfCounterWrapper(string name, string category, string counter, string instance = "")
{
_counter = new PerformanceCounter(category, counter, instance, readOnly: true);
this.Name = name;
}
public string Name { get; set; } PerformanceCounter _counter; public float Value
{
get
{
return _counter.NextValue();
}
}
}
}

注:通过nuget导入Diagnostics类库

4封装性能计数器的业务逻辑

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace SignalR.Counters
{
public class PerfCounterService
{
List<PerfCounterWrapper> _counters; public PerfCounterService()
{
this._counters = new List<PerfCounterWrapper>();
_counters.Add(new PerfCounterWrapper("Processor", "Processor", "% Processor Time", "_Total"));
_counters.Add(new PerfCounterWrapper("Paging", "Memory", "Pages/sec"));
_counters.Add(new PerfCounterWrapper("Disk", "PhysicalDisk", "% Disk Time", "_Total"));
} public dynamic GetResults()
{
return _counters.Select(c => new { name = c.Name, value = c.Value }
);
} }
}

5创建我们的工作目录-hubs并添加一个hub

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalR.Counters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web; namespace SignalR.Hubs
{
//指定该hub的名字,用于在前台中创建使用
[HubName("PerfHub")]
public class PerfHub : Hub
{
public PerfHub()
{
StartCounterCollection();
} private void StartCounterCollection()
{
Task.Factory.StartNew(async () =>
{
var perfService = new PerfCounterService();
while (true)
{
var results = perfService.GetResults();
Clients.All.newCounters(results);
await Task.Delay();
}
}, TaskCreationOptions.LongRunning);
}
//发送信息
public void Send(string name, string message)
{
Clients.All.addSomeMessage(name, message);
}
}
}

页面的内容

@model dynamic
@{
ViewBag.Title = "Index";
} <h2>Index</h2> <div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div> <script src="~/Scripts/jquery-1.6.4.js"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script type="text/javascript" src="~/signalr/hubs"></script> <script>
$(function () { // 链接hub
var chat = $.connection.PerfHub;
$.connection.hub.logging = true; $.connection.hub.start();
// 执行返回数据 perfhub中的Send中调用的方法签名一致
chat.client.addSomeMessage = function (name, message) {
// 将发送的内容显示在页面
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// 弹出输入名字的文本框
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
//启动hub的工作 $.connection.hub.start().done(function () { $('#sendmessage').click(function () {
// 发送信息
chat.server.send($('#displayname').val(), $('#message').val());
//清空输入的内容
$('#message').val('').focus();
});
});
}); function writeEvent(eventLog, logClass) {
var now = new Date();
var nowStr = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
$('#discussion').prepend('<li class="' + logClass + '"><b>' + nowStr + '</b> ' + eventLog + '.</li>');
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>