好处:1.和AJAX轮询比起来 节省资源,并且延迟小, 2.和webSocket比起来,适用的场景比较广泛。
1.先建立一个Asp.net MVC的空项目
添加一个控制器 (同样的代码在Asp.net WebForm中也是可以使用的)
复制代码 代码如下:
public class CometController : Controller
{
public ActionResult Test()
{
Response.Buffer = false;
while (true)
{
Response.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss FFF") + "|");
Thread.Sleep(500);
}
//跑不到这里的
return Content("");
}
}
}
2.再兴建一个控制器和View 用于显示HTML
复制代码 代码如下:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
View的代码比较重要
复制代码 代码如下:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script language="javascript">
var req = false;
var lastDelimiterPosition = -1;
$(document).ready(function () {
getData();
});
function getData() {
loadXMLDoc("/Comet/Test");
}
//新建一个XHR
function createRequest() {
if (window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch (e) {
req = false;
} // branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
req = false;
}
}
}
}
//发起请求
function loadXMLDoc(url) {
try {
if (req) {
req.abort();
req = false;
}
createRequest();
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send("");
} else {
alert('unable to create request');
}
} catch (e) { alert(e.message); }
}