Using jquery to implement an HTTP long connection (longpoll) {goto}

Source: Internet
Author: User
Tags date1

<%@ page language= "C #" autoeventwireup= "true" codefile= "JqueryAjaxLongPoll.aspx.cs" inherits= "Jqueryajaxlongpoll "%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<title> Untitled Page </title>
<script type= "Text/javascript" src= "Script/jquery-1.2.6.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (function () {
$ ("#Button1"). Bind ("click", {btn:$ ("#Button1")},function (evdata) {
$.ajax ({
Type: "POST",
URL: "Jqueryajaxlongpoll.aspx",
DataType: "JSON",
timeout:10000,
Data:{ajax: "1", Time: "10000"},
Success:function (data,textstatus) {
Alert ("ok!");
Evdata.data.btn.click ();
},
Complete:function (xmlhttprequest,textstatus) {
if (xmlhttprequest.readystate== "4") {
alert (Xmlhttprequest.responsetext);
}
},
Error:function (Xmlhttprequest,textstatus,errorthrown) {
$ ("#ajaxMessage"). Text ($ (this). Text () + "out!")
Alert ("Error:" +textstatus);
if (textstatus== "timeout")
Evdata.data.btn.click ();
}
});
});

/*$ ("#ajaxMessage"). Ajaxstart (function () {
$ (this). Text ("Prepare to create request. READYSTATE0:");
});
$ ("#ajaxMessage"). Ajaxsend (function (evt, request, settings) {
$ (this). Text ("Start request, ready to send data. ReadyState1:" +request.readystate);
});
$ ("#ajaxMessage"). Ajaxcomplete (function (event,request, settings) {
if (request.status==200)
$ (this). Text ("Request complete. ReadyState4:" +request.readystate);
});
$ ("#ajaxMessage"). Ajaxstop (function () {
$ (this). Text ("End of Request.");
});*/
});
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<input id= "Button1" type= "button" value= "Ajaxlongpoll"/>
<label id= "Ajaxmessage" ></label>
</div>
</form>
</body>

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Threading;

public partial class JqueryAjaxLongPoll:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
if (request.form["ajax"] = = "1")
{
Response.End ();
int time = Convert.ToInt32 (request.form["Time"]);
DateTime date1 = DateTime.Now.AddMilliseconds ((double) time);
BOOL ready = FALSE;
while (response.isclientconnected)
{
Thread.Sleep (3000);
if (Datetime.compare (Date1, DateTime.Now) < 0)
{
Response.End ();
Break
}
Ready = true;
if (Ready)
{
Response.Write ("SetValue ('" + DateTime.Now.ToString () + "')");
Response.Flush ();
Response.End ();
Break
}
Else
{

}
}
}
Else
{
if (! Page.IsPostBack)
{

}
}
}
}

Ideas:

With jquery, it is convenient to implement Ajax, which set the timeout time for Ajax, because setting a timeout will not be able to maintain a long connection, to the time of the Ajax automatically reported "timeout" error, that is, will call error method, At this point textstatus== "timeout", after timeout, re-make the AJAX request. When the server accepts an AJAX request, it receives a value for the time-out, and the server-side processing stops immediately. When the client successfully obtains the return result, a new AJAX request is also made immediately, so loop.

Why set the Ajax timeout value for the client? Because the server in order to maintain the request (blocking the request), there must be an infinite loop, the end condition of the loop is to obtain the return result, if the client is closed (the client browser is closed will not send a message to the server), the server can not know that the client has been shut down, the request is not necessary to deal with. The end result is excessive waste of resources, as long as a compromise method, limit the time-out.

you can not set the client Ajax timeout time, but when the request to pass a time-out value to the server, when the server processing, if the time-out period, there is no client needs the results, then pass a timeout information to the client, the client received this information, Re-make the AJAX request as appropriate. XMLHttpRequest does not have timeout parameters, jquery is packaged in Window.settimeout itself (to the timed time-out processing method, and the XMLHttpRequest End method). Can be based on this idea to change a bit, IBM introduced on the long poll seems to be the case.

$ (document). Ready (function () {
$ ("#Button1"). Bind ("click", {btn:$ ("#Button1")},function (evdata) {
$.ajax ({
Type: "POST",
URL: "Jqueryajaxlongpoll.aspx",
DataType: "JSON",
Data:{ajax: "1", Time: "6000000"},
Success:function (data,textstatus) {
Success
if (data.success== "1") {
Client processing
//...
Re-request
Evdata.data.btn.click ();
}
Timeout
if (data.success== "0") {
Evdata.data.btn.click ();
}
},
Complete:function (xmlhttprequest,textstatus) {
if (xmlhttprequest.readystate== "4") {
alert (Xmlhttprequest.responsetext);
}
},
Error:function (Xmlhttprequest,textstatus,errorthrown) {
$ ("#ajaxMessage"). Text ($ (this). Text () + "out!")
Alert ("Error:" +textstatus);
if (textstatus== "timeout")
Evdata.data.btn.click ();
}
});
});

After the background code changes:
if (request.form["ajax"] = = "1")
{
int time = Convert.ToInt32 (request.form["Time"]);
DateTime date1 = DateTime.Now.AddMilliseconds ((double) time);
BOOL ready = FALSE;
while (response.isclientconnected)
{
Thread.Sleep (3000);
if (Datetime.compare (Date1, DateTime.Now) < 0)
{
Response.Write ("{success: ' 0 '}");
Response.End ();
Break
}
The request is processed here and the result is set Ready = True
Ready = true;
if (Ready)
{
Response.Write ("{success: ' 1 '}");
Response.End ();
Break
}
}
}
Else
{
if (! Page.IsPostBack)
{

}
}

The above method should be able to meet the requirements, the specific time-out can be set according to the situation. This is also I based on the IBM introduction of the "Server Push" idea, to achieve one of them, do not know if there is a problem, but also please give us a lot of comments.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.