大家都知道HTTP是响应式通讯的,只有浏览器请求服务器后服务器才会响应,不会主动从服务器推送内容到浏览器来,不过很多实际的需求是需要服务器主动推送内容到浏览器,例如我们公司在做一个机房实时监控的系统,需要实时的把机房的异常信息推送到浏览器,于是我引入了一个.net的推送框架SignalR。
ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程。实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务器代码可以立即向其推送内容,而不是让服务器等待客户端请求新的数据。
以上都是废话,详情看下面:
1、新建一个项目
.net版本是.net4.5 其他没什么好注意了
2、添加SignalR框架
添加完了知乎会如下图所示
3、接下来我们添加一个SignalRHub.cs文件
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SignalRServer
{
public class SignalRHub:Hub
{
public void SendAll(string message)
{
Clients.All.message(message);
}
}
}
4、添加Startup.cs文件
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;
[assembly: OwinStartup(typeof(SignalRServer.Startup))]
namespace SignalRServer
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration{};
map.RunSignalR(hubConfiguration);
});
}
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Dome</title>
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script>
$(function () {
var connection = $.connection.signalRHub;
connection.client.message = function (message) {
$("#message").append("<li>" + message + "</li>");
};
$.connection.hub.start().done(function () {
$("#s").click(function () {
connection.server.sendAll($("#m").val());
})
})
})
</script>
</head>
<body>
<label><input type="text" id="m" /><input type="button" id="s" value="发送" /></label>
<ul id="message"></ul>
</body>
</html>
新建一个asp.net的网站然后添加Index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Dome</title>
<script src="http://192.168.1.118:8002/Scripts/jquery-1.6.4.min.js"></script>
<script src="http://192.168.1.118:8002/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://192.168.1.118:8002/signalr/hubs"></script>
<script>
$(function () {
$.connection.hub.url = "http://192.168.1.118:8002/signalr/hubs";//如果是跨域必须注明来源的地址
var connection = $.connection.signalRHub;
connection.client.message = function (message) {
$("#message").append("<li>" + message + "</li>");
};
$.connection.hub.start().done(function () {
$("#s").click(function () {
connection.server.sendAll($("#m").val());
})
})
})
</script>
</head>
<body>
<label><input type="text" id="m" /><input type="button" id="s" value="发送" /></label>
<ul id="message"></ul>
</body>
</html>
这样就可以了。
这里有个Dome,不过不知怎么上传;
相关的官网API http://www.asp.net/signalr/overview/getting-started