利用Jquery实现http长连接(LongPoll)

时间:2024-11-07 15:38:14

参考:http://www.cnblogs.com/vagerent/archive/2010/02/05/1664450.html

PS:为了满足某些需要实时请求的业务(PS:例如聊天室),我们可以通过多种技术实现, 其中建议大家使用长链接(PS:减少带宽)或者服务器主动推送技术(例如:Signalr)。

这里只对长链接进行陈述,参考上面的博客写了个Demo如下(复制到项目里面可以直接运行):

新建一个 Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LongPool.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body> <input type="button" id="Button1" value="AjaxLongPoll" />
<label id="ajaxMessage"></label>
</body>
</html>
<script src="Scripts/jquery-1.8.2.js"></script>
<script>
$(function () {
$("#Button1").bind("click", { btn: $("#Button1") }, function (evdata) { $.ajax({
type: "POST",
url: "Default.aspx",
data: { ajax: "", time: "" },
success: function (data, textStatus) {
var _rec = $.parseJSON(data);
//成功
if (_rec.success == "") {
//客户端处理
alert("ok");
///重新请求
evdata.data.btn.click();
}
//超时
if (_rec.success == "") {
evdata.data.btn.click();
}
},
complete: function (XMLHttpRequest, textStatus) {
if (XMLHttpRequest.readyState == "") {
//alert(XMLHttpRequest.responseText);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//$("#ajaxMessage").text($(this).text()+" out!") alert(textStatus);
evdata.data.btn.click();
}
});
});
})
</script> using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace LongPool
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["ajax"]=="")
{
int time = Convert.ToInt32(Request.Form["time"]);
DateTime date1 = DateTime.Now.AddMilliseconds(time);
bool ready = false;
int n = ;
while (Response.IsClientConnected)
{
Thread.Sleep();
if (DateTime.Compare(date1,DateTime.Now)<)
{
Response.Write("{\"success\":0}");
Response.End();
break;
}
//此处进行请求处理,有结果了置ready = true
ready = true;
if (ready)
{
Response.Write("{\"success\":1}");
Response.End();
break;
}
}
}
else
{
if (!IsPostBack)
{ } }
}
}
}