目的:使用实时推送数据
原文:https://www.cnblogs.com/dathlin/p/9026680.html
1.引用:SignalR程序集(官网介绍:https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/getting-started/introduction-to-signalr)
2.添加一个类:Startup.cs
用于作为SignalR程序启动的顺序(App启动主程序)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApplication1.Startup))]
namespace WebApplication1
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
app.MapSignalR();
}
}
}
3.新建文件夹Hubs,并在里面添加MyHub类:
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
namespace WebApplication1.Hubs
{
[HubName("myHub")]
public class MyHub : Hub
{
// Is set via the constructor on each creation
private Broadcaster _broadcaster;
public MyHub()
: this(Broadcaster.Instance)
{
}
public MyHub(Broadcaster broadcaster)
{
_broadcaster = broadcaster;
}
}
/// <summary>
/// 数据广播器
/// </summary>
public class Broadcaster
{
private readonly static Lazy<Broadcaster> _instance =
new Lazy<Broadcaster>(() => new Broadcaster());
private readonly IHubContext _hubContext;
private Timer _broadcastLoop;
public Broadcaster()
{
// 获取所有连接的句柄,方便后面进行消息广播
_hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
// Start the broadcast loop
_broadcastLoop = new Timer(
BroadcastShape,
null,
1000,
1000);
}
private Random random = new Random();
private void BroadcastShape(object state)
{
//int[] values = new int[10];
//for (int i = 0; i < values.Length; i++)
//{
// values[i] = random.Next(100);
//}
//// 定期执行的方法
//_hubContext.Clients.All.sendTest1(values);
////推送Json
////JObject json = new JObject();
////json.Add("A", random.Next(1000, 10000).ToString());
////json.Add("B", random.Next(20).ToString());
//// 定期执行的方法
////_hubContext.Clients.All.sendTest1(json);
// 定期执行的方法
_hubContext.Clients.All.sendTest1(random.Next(1000).ToString()); //定期推送随机数
}
public static Broadcaster Instance
{
get
{
return _instance.Value;
}
}
}
}
4.index.chtml
@{
ViewBag.Title = "Home Page";
}
<div id="test">这里即将显示服务器推送的数据</div>
@section scripts {
<script src="~/Scripts/jquery.signalR-2.4.0.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function () {
var mypush = $.connection.myHub;
mypush.client.sendTest1 = function (message) {
$("#test").text(message);
console.log(message);
};
$.connection.hub.start();
});
</script>
}