Asp.net server push and client pull

Source: Internet
Author: User

In the past communication technologies with servers, we used AJAX round-robin access, that is, controlling the time interval in Javascript, and then accessing the server at intervals, then obtain the data or notification. However, 90% of the requests in this round robin method are useless.
What should I do if I want to maintain the connection between the server and the browser for a long time? Persistent connection technology is not a new technology. Using IFrame as a method to hide frames pointing to long request pages has already been used by many people on the Internet. However, IFrame as a hidden frame has a drawback, that is, the progress bar of the browser is always in the Read state. To provide a better user experience, "Google talents" used an object named "htmlfile" to solve this problem and applied it to two products, GMail and GTalk.
Now our company needs to implement real-time alarm functions for new projects. I originally wanted to use AJAX Round Robin, but I felt quite unpursued. I heard that Server Push was available some time ago, but I did not study it carefully. This is a chance to collect data from the Internet in one day. There are not a lot of materials, and many developers still think that persistent connections are a fantasy, and they still need to prove their point of view by moving the HTTP protocol out ......
Let's talk about the persistent connection technology. The common persistent link is to create a webpage, which has an IFrame tag, and the height and width are set to 0. The SRC attribute points to a webpage, for example, it is ASPX, And then it does not do anything in this file, just calling Context. response. write method. What is output? For example, if the client has a Change (time) method, the output is ("<script> window. parent. change ("+ DateTime. now. toString () + ") </script>"), that is, the function calls of the client are continuously output and made into an endless loop, in this way, the browser and the server form a continuous stream of data transmission links .; What is htmlfile? This is an ActiveXObject similar to the Window object in Javascript. It is also in the DOM structure and writes the IFrame as the hidden frame to this object to solve the progress bar problem. It may be obscure. Let's look at the instance code:
Default. aspx. cs
 
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
}
Protected override void Render (HtmlTextWriter output)
{
String str;
While (true)
{// Keep a persistent link in an endless loop
Str = "<script> window. parent. Change ('" + DateTime. Now. ToLongTimeString () + "') </script> ";
This. Context. Response. Write (str );
This. Context. Response. Flush (); // input the script to call
System. Threading. Thread. Sleep (1000 );
}
}
}
Copy code
WebForm1.aspx
<! 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> Asp.net Server Push </title>
<Script type = "text/javascript">
Function Change (str ){
Optional bytes Doc ument. getElementById ("div1"). innerText = str;
}
Function onload (){
Var ifrpush = new ActiveXObject ("htmlfile"); // create an object
Ifrpush. open (); // open
Var ifrDiv = ifrpush. createElement ("div"); // Add a DIV
Ifrpush. appendChild (ifrDiv); // Add to htmlfile
Ifrpush. parentWindow. Change = Change; // The javascript registration method does not understand why you need to register
IfrDiv. innerHTML = "<iframe src = 'default. aspx '> </iframe>"; // Add iframe to the div
Ifrpush. close (); // close
}
Onload ();
</Script>
</Head>
<Body>
<Div style = "float: left"> current time: </div>
<Div id = "div1"> </div>
</Body>
</Html>
Copy code
Server Push)
The basic idea of push technology is to change the browser's active query information to the server's active sending information. The server sends a batch of data, the browser displays the data, and ensures the connection with the server. When the server needs to send a batch of data again, the browser displays the data and keeps the connection. In the future, the server can still send batch data, and the browser will continue to display the data, and so on.
Client Pull (Client Pull)
In the client drag technology, the server sends a batch of data and inserts instructions in the HTTP response or document header flag, let the browser "load the data again within five seconds" or "load data to a URL within 10 seconds ". When the specified time is reached, the client performs the operation as instructed by the server, refreshes the current data, or transfers new data.
 
In fact, the push and pull technologies are very different, but the goal is almost the same, in order to provide end users with the latest information conveniently.
In server push technology, HTTP connections remain until the server knows that it has ended sending data and sending an end signal, or the client has interrupted the connection. In the client drag technology, HTTP connections are not maintained. On the contrary, the client is notified of how to create a new connection and what data to obtain when a connection is established.
 
In server push, what's amazing is the MIME in the multipart/mixed format. It can make a message (or HTTP Response) contain many data items and drag them on the client, what's amazing is that the HTTP Response Header (or equivalent HTML element) can tell the client what action to perform after the specified delay.
Server push is generally more efficient than client drag because it does not have to create new connections for subsequent data. Because the connection is always maintained, even if there is no data transmission, the server must be willing to allocate these TCP/IP ports, this is a serious problem for servers with a limited number of TCP/IP ports.
 
Client drag efficiency is low, because this must create a new connection for each data transfer. However, it does not have to always maintain the connection.
 
In practice, it usually takes a considerable amount of time to establish an HTTP connection, as many as one second or even more. Therefore, in terms of performance, server push is more attractive to end users, especially when information needs to be updated frequently.
Another advantage of server push over client dragging is that server push is relatively easy to control. For example, the server maintains a connection for each push, but it can close any connection at any time without setting special algorithms on the server. In the same situation, client dragging requires a lot of trouble. It needs to establish a connection with the server every time, and the server matches the client dragging request with a specific end user in order to process the situation, requires a very troublesome algorithm.
 
If the CGI program pushed by the server is written in Shell script language, some problems may occur sometimes. For example, if the client end user breaks the connection, the Shell program usually cannot notice it, which will waste resources for no use, to solve this problem, you can use Perl or C to write these CGI programs so that the user can stop running when the connection is interrupted.
 
 

As mentioned above, connections are always maintained among multiple responses in server push so that the server can send more data at any time. One obvious benefit is that the server can fully control the time and frequency of data update. In addition, this method is highly efficient because the connection is always maintained. The disadvantage is that maintaining the connection will waste resources on the server. Server push is easy to interrupt.
 
Next, let's talk about the server push technology.
When the server responds to a request, HTTP uses the MIME Message format to encapsulate data. Generally, an HTTP response can only contain one data block. However, there is a mechanism for MIME to use one message (or HTTP Response) to represent multiple data blocks. This mechanism is a standard MIME type of "multipart/mixed. The general format of multipart/mixed packets is as follows:
Content-type: multipart/mixed; boundary = ThisRandomString
-- ThisRandomString
Content-type: text/plain
The data of the first object.
-- ThisRandomString
Content-type: text/plain
The data of the second object.
-- ThisRandomString --
 
The preceding message includes two data blocks, both of which are "text/plain ". The two short-term messages (--) after the last "ThisRandomString" indicate that the packet ends and there is no data.
 
For server push, a multipart/x-mixed-replace variant of the multipart/mixed type is used. Here, "x-" indicates the lab type. "Replace" indicates that each new data block replaces the previous data block. That is to say, the new data is not appended to the old data, but replaced by it.
 
The following is the actual "multipart/x-mixed-replace" type:
Content-type: multipart/x-mixed-replace; boundary = ThisRandomString
-- ThisRandomString
Content-type: text/plain
Data of the first object
-- ThisRandomString
Content-type: text/plain
The data of the second (last) object.
-- ThisRandomString --
The key to using this technology is that the server does not push the entire "multipart/x-mixed-replace" packet, but the data block after each transmission.
The HTTP connection is always maintained, so the server can push new data at the desired speed and frequency. The browser only needs to wait in the current window between the two data blocks, users can even do other things in other windows. When the server needs to send new data, it only sends data blocks from the source (ABC input method does not have that word * & ^ $ #) transmission pipeline, update the window corresponding to the client.
 
In server push technology, "multipart/x-mixed-replace" messages are composed of unique boundaries that divide each data block. Each data block has its own header, so it can specify the content type and other information related to the object. Because the "multipart/x-mixed-replace" feature is that each new data block replaces the previous data object, the browser always displays the latest data object.
The "multipart/x-mixed-replace" message does not end. That is to say, the server can always maintain the connection and send the required data. If the user no longer displays data streams in the browser window, or connects the browser to the server (for example, the user presses the "STOP" button), the server push will be interrupted. This is a typical way for people to use server push.
 
When the browser finds the Content-type header or reaches the end of the header, the previous document in the browser window is cleared and the next document is displayed. When the next message boundary is found, the current data block (document) is deemed to have ended.
In short, the data pushed by the server is composed of a set of header labels (usually including "Content-type"), the data itself, and the delimiter (Message boundary. When the browser sees the delimiter, it remains unchanged until the next data block arrives.
 
The above concepts can be implemented by programming to obtain the actual server push program. For example, the following Unix shell program enables the browser to display the process list on the server every 5 seconds:
#! /Bin/sh
Eecho "HTTP/1.1 200"
Cecho "Content-type: multipart/x-mixed-replace; boundary = -- ThisRandomString --"
Echo ""
Oecho "-- ThisRandomString --"
While true
Do
Echo "Content-type: text/html"
Echo ""
Echo "h2Processes on this machine updated every 5 seconds/h2"
Echo "time :"
Date
Echo "p"
Echo "plaintext"
Ps-el
Echo "-- ThisRandomString --"
Sleep 5
Done
Note that the boundary setting is sent before the sleep statement, which ensures that the browser clears its buffer and displays the latest data received.
Ncsa httpd users cannot use spaces in the content type, including boundary parameters. Ncsa httpd can only use a string without spaces as the content type. If there is a space in the content type line (except for spaces after the colon), any text after the space will be deleted. The following example is correct:
Content-type: multipart/x-mixed-replace; boundary = ThisRandomString
The following example does not work properly because it has spaces in the middle:
-Type: multipart/x-mixed-replace; boundary = ThisRandomString
Another advantage of server push is that it can be applied to a single inline image. Documents including images can be updated by the server at regular or periodic intervals. The implementation is very simple: you only need to direct the SRC attribute of the IMG element to the URL that pushes a series of images. If the server pushes a Single Inline image, the image in the document will be replaced by the newly pushed image again and again, and the document itself does not need to change (assuming that the document is not pushed to the server ). In this way, limited animations on WEB pages can be replaced by static images.
Client drag
One simple way to drag a client is to automatically reload the document at a fixed period. For example, consider the following HTML document:
<META HTTP-EQUIV = "Refresh" CONTENT = 1>
<TITLE> Document ONE </TITLE>
<H1> This is Document ONE! </H1>
Here's some text. <P>
If you load it into a browser that supports dynamic documents (Netscape 1.1 or above, Internet Explorer and Mosaic also support client dragging), it will reload itself once every second.
The META element simulates the HTTP Response Header in the HTML document, so it can tell the browser to use its own information as an HTTP response. The META tag in the above example is equivalent:
Refresh: 1
In this way, the HTTP header tells the browser to update the document every second. If the latency is 12 seconds, the following command is used:
<META HTTP-RQUIV = "Refresh" CONTENT = 12>
So it is equivalent to: Refresh: 12

I am also lazy to write down the drag of the client. Please use the following to learn how to enable the client to automatically apply for data from other URLs:
<META HTTP-EQUIV = "Refresh" CONTENT = "12; URL = http://icools.yeah.net/">
Note that the URL here cannot use relative paths and must all be specified.
The time interval can be set to 0, so that the browser loads new data as quickly as possible after the current document is displayed!

 

From Jiabo

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.