Comet: jquery + Asp.net implement HTTP persistent connection (longpoll)

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">

<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
<SCRIPT type = "text/JavaScript" src = "scripts/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 a request. readystate0 :");
});
$ ("# Ajaxmessage"). ajaxsend (function (EVT, request, settings ){
$ (This). Text ("START request, prepare to send data. readystate1:" + request. readystate );
});
$ ("# Ajaxmessage"). ajaxcomplete (function (event, request, settings ){
If (request. Status = 200)
$ (This). Text ("request completed. readystate4:" + request. readystate );
});
$ ("# Ajaxmessage"). ajaxstop (function (){
$ (This). Text ("request ended .");
});*/
});
</SCRIPT>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Input id = "button1" type = "button" value = "ajaxlongpoll"/>
<Label id = "ajaxmessage"> </label>
</Div>
</Form>
</Body>
</Html>

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)
{

}
}
}
}

Code Description: Using jquery, you can easily implement Ajax. The preceding setting sets the Ajax timeout time. A long connection cannot be maintained because timeout is set, by the time Ajax automatically reports a "timeout" error, that is, the error method is called. In this case, textstatus = "timeout" and timeout are used to re-request Ajax. When the Server accepts an Ajax request, it receives a timeout value. When the request times out, the server stops processing the request immediately. When the client successfully obtains the returned results, it will immediately initiate a new Ajax request.

Why do I need to set the Ajax timeout value for the client? The server must have an infinite loop to keep requests (blocking requests). The end condition of the loop is to get the returned results, if the client is closed (the client browser is closed and no message is sent to the server), the server cannot know that the client is closed and the request does not need to be processed. In the end, excessive resource waste will occur. You only need to use a compromise to limit the timeout.

You do not need to set the client Ajax timeout, but pass a timeout value to the server during the request. When the server is processing the request, if the timeout time is reached, there is no result required by the client, at this time, a timeout message is sent to the client. The client receives this information and re-Requests Ajax based on the situation. XMLHttpRequest does not have a timeout parameter. jquery uses window. setTimeout to encapsulate it (the processing method for running the timeout at the scheduled time, And the XMLHttpRequest end method ). The long poll introduced on IBM seems to be the same.

$ (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 ){
// Succeeded
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 is changed:
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;
}
// Process the request here. If ready = true is returned
// 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, and the specific timeout time can be set according to the situation. This is also one of the ways I have implemented server push based on the "server push" ideas introduced by IBM. I do not know if there are any problems. Please give me more advice.

Related Article

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.