Instant tips for Web sites with jquery Ajax and. Net IHttpAsyncHandler

Source: Internet
Author: User
Tags httpcontext

The project has been done for some time, has been wanted to write a summary of the blog, has not written a quality blog. One is afraid of writing to be a joke, and the second is because afraid that they only understand a little fur on the issue to mislead others, so has not been how to write a blog, but see a lot of Daniel encourages programmers to write blogs, One can review the focus of the project you do, and you can find a lot of problems that you haven't found before. So try to write it yourself, have not summed up the habit, also want to change. The writing is not good, the experience lacks, everybody lightly sprays.

-----------------------------------------------------Split Line-----------------------------------------------

Because of the needs of the project, the supervisor asked me to do a post-login instant alert function, that is, when the data changes, notify the user immediately. Then I started Baidu, Google's various keyword searches. Finally, there are several ways to achieve this. That is, polling and long connections. There is also an open-source framework provided by Microsoft SIGNALR (currently the landlord himself knows these).

Because of the stateless nature of HTTP, there is no connectivity. The data transfer between the Web program and the server can only be: The browser sends a request to the server, the server responds to the request, and then returns the information to be requested. That is, the relationship between the browser and the server is a request-response relationship, the benefit of which is not said ( I also know not much--!), but the server can not actively send data to the browser, because it is stateless. What if there is such a demand? There are a lot of smart people, and the smart guys come up with a way to solve them. Walnuts posterity, let's start by trying out which option is best for the project.

1.signalr

The garden has already had the introduction SignalR article: SignalR Project Introduction is Zhang Shanyu teacher writes

I implemented push functionality by using SignalR in ASP. This article learned about the specific use of the method, there is no deep research, it is suitable for Web instant chat.

Landlord's project is to achieve similar monitoring database functions, so do not consider this method , interested friends can go to understand.

2. Polling

The so-called polling is that the client keeps sending asynchronous requests to the server, and notifies the browser when there are changes to the database. This method is simple to implement, but also know that because it is constantly sending requests to the server, for the server is the pressure Alexander, if the Web page too many words, May cause a server crash.

3. Long connection

The first two methods are not LZ want, it seems that LZ can only sacrifice that one trick: Long connection.

The landlord is Baidu Google Party, pick a netizen words to explain long connection: The client sends a request to the server, the server receives the request and hlod the connection, until there is data or request time-out to return to the client, the client then sends another request, so loop until the page closes, This also explains why it is called a long connection. For example, this picture:

The first two requests for this graph timeout I set to 1 minutes and then send a request immediately after returning.

Well, since there's only one final trick left, it's a good trick

The first is for the client to send an asynchronous request:

/*asynchronous requests made by the client*/            functionasyncrequest () {$.ajax ({type:"POST", URL:"Asyncresult.asyn", Data:"Time=60",//Request time-outSuccessfunction(data) {if(Data! = "") {                            /*perform actions such as pop-up hints*/} asyncrequest (); //continue to send a request after receiving the server response}, Error:function() {asyncrequest ();//a request continues to be sent after the server throws an error                    }                }); }

The server receives this asynchronous request method also to implement the asynchronous operation, otherwise will block the normal request, therefore implements the IHttpAsyncHandler this interface, realizes the server asynchronous computation.

 Public classAsyncresponse:ihttpasynchandler { PublicIAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback CB,Objectextradata) {Myasyncresult result=NewMyasyncresult (Context, CB, Extradata);            Asyncrequestmgr.add (result);            Asyncrequestmgr.send (); returnresult; }         Public voidendprocessrequest (IAsyncResult result) {Asyncrequestmgr.resultstr="";//empty results at end of asynchronous        }         Public BOOLisreusable {Get{return false; } }         Public voidProcessRequest (HttpContext context) {}}

The Asyncresponse class is used to receive all asynchronous requests and is handed to the static class asyncrequestmgr to calculate the results on request:

 Public Static classAsyncrequestmgr { Public Static stringResultStr =""; Private StaticMyasyncresult AsyncResult; /// <summary>        ///saves an asynchronous request object to a static object for manipulation/// </summary>        /// <param name= "result" ></param>         Public Static voidAdd (myasyncresult result) {AsyncResult=result; }        /// <summary>        ///         /// </summary>         Public Static voidSend () {stringTime = asyncresult.contex.request.form[" Time"];            GetResult (time);    Asyncresult.send (RESULTSTR); //sending data to the client        }        /// <summary>        ///get results or return null values/// </summary>        Private Static voidGetResult (stringTime ) {            inti =int. Parse (time), temp =0;  while(Temp <i) {Thread.Sleep ( +);//This class inherits from IHttpAsyncHandler, which is the thread pool that takes out a thread to execute this class, so that the thread sleep (1000) does not affect the UI thread                /** Here to query the database, get the data to save to the variable resultstr, and then break out of the loop,*/temp++;
} } }

The result is then sent by the Myasyncresult class:

  Public classMyasyncresult:iasyncresult { PublicHttpContext Contex;  PublicAsyncCallback CB;  Public ObjectExtradata; /// <summary>        ///Initializing Data/// </summary>        /// <param name= "Contex" ></param>        /// <param name= "CB" ></param>        /// <param name= "Extradata" ></param>         PublicMyasyncresult (HttpContext Contex, AsyncCallback CB,Objectextradata) {             This. Contex =Contex;  This. cb =CB;  This. Extradata =Extradata; }        /// <summary>        ///returns the data requested by the client/// </summary>         Public voidSendstringresultstr) {             This. Contex.        Response.Write (RESULTSTR); }    }

Such an asynchronous request, even if completed, also implements the purpose of monitoring the database, but if the customer accidentally in the background to query the database when the refresh what to do? This connection will be broken, and because my foreground is the page load when the asynchronous request, the refresh will send another request, The first query in the background continues. This way the background will have two requests to execute together, query the database together. If the database changes are queried for the first time, but the first request is made because the customer refreshes the page, the connection is disconnected, and the user cannot be notified of the data changes. If the user is not careful (hand) meaning (cheap) has been pressed F5, the front desk will always refresh the request, the background of n requests at the same time to check the database. And then if there are 10 users at the same time press F5, that is 10*n a request at the same time to check the database, the last server can only be overwhelmed collapse, if so how to do? Because the LZ usually see less MSDN, indeed distressed for a while, and finally suddenly found that Httpcontext.response has a property: IsClientConnected, this property helps a lot, it returns a bool value that indicates whether the current request is in a connected state. With this attribute is good to do, in the GetResult method to add the judge, if Isclientconnected==false, immediately throw an exception, and then save the results of the query to the RESULTSTR variable, so that the thread will not continue to execute.

The modified GetResult method:

/// <summary>        ///get results or return null values/// </summary>        Private Static voidGetResult (stringTime ) {            inti =int. Parse (time), temp =0; Try{
while (Temp < i)
{
  if(!asyncResult.contex.Response.IsClientConnected)Throw NewException (); Thread.Sleep ( +);//This class inherits from IHttpAsyncHandler, which is the thread pool that takes out a thread to execute this class, so that the thread sleep (1000) does not affect the UI thread /** Here to query the database, get the data to save to the variable resultstr, and then break out of the loop,*/
temp++; } } Catch(Exception) {/*This saves the results from the exception thread to ResultStr .*/ Throw; } }

Then before the Send method to determine whether ResultStr is empty, if not empty, you do not have to query the database, send resultstr directly:

 /// <summary>        ///         /// </summary>         Public Static voidSend () {if(ResultStr = ="")            {                stringTime = asyncresult.contex.request.form[" Time"];            GetResult (time);    } asyncresult.send (RESULTSTR); //sending data to the client}

This way, no matter how long the F5, as long as the server to determine which request the connection status of false throws an exception, keep at most only one request to query the database, now even if no () () F5 also not afraid!

----------------------------------------Split Line-------------------------------------

The first time I think it is a technical post, if you think I understand what is wrong please point out in time to avoid misleading others.

Instant tips for Web sites with jquery Ajax and. Net IHttpAsyncHandler

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.