Server ' push ' technology in HTML5-server-sent Events

Source: Internet
Author: User

Reprint: http://www.developersky.net/thread-63-1-1.html

All along, the HTTP protocol is strictly following the Request-response model. The client sends a request to the server, the server responds to the request and sends the response back to the client. In other words, all interactions are initiated by the client and the server does not initiate any interaction.
In order to create a more interactive Web application, Ajax came into being, and Ajax implemented a dynamic way to get data from the server. By using AJAX, the browser sends an HTTP request via the XMLHttpRequest API. XMLHttpRequest allows us to send an asynchronous HTTP request to the server without blocking the user interface to get the data. However, Ajax does not define a new HTTP request type, but moves the HTTP request to the background without affecting the user's operation. So Ajax does not break the Request-response model, or the browser pulls the data from the server.
Another technique is comet, also known as reverse Ajax. Like Ajax, Comet is built on an already existing HTTP protocol. Comet maintains a long-lived HTTP connection, sending a ' fake ' request to get response.
These are the workarounds to break the limits of the HTTP protocol. But inHTML5, this restriction will be broken. The HTML5 specification includes many powerful features that enable the browser to become a fully functional RIA client platform. The server-sent event and WebSockets are among the two features that can help us implement the server 's ability to ' push ' the data to the client.
In this article, let's first introduce the Server-sent events feature
Server-sent Events
Server-sent events actually standardizes Comet technology. The Server-sent Events Specification "defines an API to open an HTTP connection that enables you to get notifications pushed from the server." Server-sent events contains the new HTML element EventSource and the new MIME type Text/event-stream, which defines the format of the event framework.

<HTML>   <Head>     <Mce:scripttype= ' Text/javascript '><!--var Source = new EventSource (' Events ');           Source.onmessage = function (event) {ev = document.getElementById (' events ');        ev.innerhtml + = "<br>[in]" + event.data;     }; //  -</Mce:script>  </Head>  <Body>    <DivID= "Events"></Div>  </Body></HTML>

EventSource represents the endpoint of the client receiving the event. The client opens an event stream by creating a EventSource object. When you create a EventSource object, the object receives the URL of an event source as a parameter to its constructor. The OnMessage event handler is called each time a new event data is received.
Typically, the browser restricts the number of connections to each server. In some cases, loading multiple pages that contain EventSource objects to the same domain causes a connection to be created for each EventSource that is dedicated to that EventSource, which in this case will soon exceed the limit on the number of connections. To handle this, we can use the shared Webworker, which shares an instance of EventSource. In addition, by defining browser-specific EventSource implementations, we can do so if the URLs of the two EventSource are the same, then they reuse the same connection. At this point, the shared connection is managed by the browser-specific EventSource implementation.
When the event stream is opened, the browser sends the following HTTP request.
REQUEST:

Get/events http/1.1host:myserver:8875user-agent:mozilla/5.0 (Windows; U Windows NT 5.1; De-de)         applewebkit/532+ (khtml, like Gecko) version/4.0.4         Safari/531.21.10accept-encoding:gzip, Deflatereferer:http://myserver:8875/accept:text/event-streamlast-event-id:6accept-language:de-decache-control: No-cacheconnection:keep-alive   

The accept defines the required format Text/event-stream. Although the Server-sent events specification defines the MIME type of Text/event-stream, the specification also allows the use of other event framework formats. However, the implementation of Server-sent events must support the Test/event-stream format.
Depending on the format of the Text/event-stream, an event has one or more comment lines and a word marked field composition. The comment line is a line that begins with a colon:. Field fields are made up of field names and field values, and field names and field values are separated by colons: Multiple events are separated by a blank line. Here is an example of a response:
RESPONSE:

http/1.1 Okserver:xlightweb/2.12-html5preview6content-type:text/event-streamexpires:fri, Jan 1990 00:00:00 Gmtcache-control:no-cache, No-store, max-age=0, Must-revalidatepragma:no-cacheconnection:close:time streamretry: 5000id:7data:thu Mar 07:31:30 cet 2010id:8data:thu mar one 07:31:35 cet 2010[...]

By definition, the Event stream should not be cached. To avoid caching, Cache-control is included in the header of response, which disables caching of the response.
In the example above, the response contains three events. The first event contains a comment line and a retry field, and the second and third events consist of an ID field and a data field. The data field contains the information of the event, which is the current time in the example above. The ID field is used to track the processing process in the event stream. In the example above, the server-side application writes an event to the event stream every 5 seconds. When the event is received by EventSource, the OnMessage event handler is called.
The difference is that the first event does not trigger a onmessage processor. The first event has no data field, contains only one comment line and one retry field, and the Retry field is used for reconnection purposes. The retry field defines the time to reconnect, in milliseconds. If such a field is received, EventSource updates the properties of its associated reconnection time. In the event of a network error, reconnection time plays an important role in improving reliability. When the EventSource instance discovers that the connection is broken, the connection is automatically rebuilt after the specified reconnection time.
As we can see, in HTTP request, we can specify Last-event-id. EventSource The value is specified when the connection is rebuilt. Each time EventSource receives an event that contains an ID field, the last Event ID property of EventSource is changed, and when the connection is rebuilt, the last event ID attribute of EventSource is written to the HTTP In the Last-event-id of the request. This way, if the server side implements Lasteventid processing, it is guaranteed that the received events will not be sent in the rebuilt connection.
The following code is an example of a httpserver based on the Java HTTP library Xlightweb (including the HTML5 Preview extension).

class Serverhandler implements Ihttprequesthandler {Private final timer timer = new timer (false); public void ONrequest (Ihttpexchange Exchange) throws IOException {String RequestUri = Exchange.getrequest (). getrequest    URI ();    if (Requesturi.equals ("/serversenteventexample")) {Sendserversendpage (Exchange, RequestUri);    } else if (Requesturi.equals ("/events")) {Sendeventstream (Exchange);    } else {exchange.senderror (404); }} private void Sendserversendpage (Ihttpexchange exchange, string uri) throws IOException {String page = "<HTML>/r/n "+"<Head>/r/n "+"<Mce:scripttype= ' Text/javascript '><!--/r/n "+" var Source = new EventSource (' Events ');/r/n "+" source.onmessage = function (ev ENT) {/r/n "+" EV = document.getElementById (' events ');/r/n "+" ev.innerhtml + =/"<br& Gt [In]/"+ event.data;/r/n" + "};/r/n" + "// -</Mce:script>/r/n "+"</Head>/r/n "+"<Body>/r/n "+"<DivID=/"events/"></Div>/r/n "+"</Body>/r/n "+"</HTML>/r/n ";  Exchange.send (New HttpResponse (, "text/html", page));    private void Sendeventstream (final Ihttpexchange Exchange) throws IOException {//Get the last ID string    Final String idstring = Exchange.getrequest (). GetHeader ("Last-event-id", "0"); Sending the response header final Bodydatasink sink = exchange.send (new Httpresponseheader, "Text/ev    Ent-stream "));       TimerTask tt = new TimerTask () {private int id = integer.parseint (idstring);           public void Run () {try {event event = new event (new Date (). toString (), ++id);         Sink.write (Event.tostring ());           } catch (IOException IoE) {cancel ();         Sink.destroy ();    }       };    };    Event Event = new event ();    Event.setretrymillis (5 * 1000);    Event.setcomment ("Time Stream");    Sink.write (Event.tostring ());  Timer.schedule (TT, 3000, 3000); }}xhttpserver Server = new Xhttpserver (8875, New Serverhandler ()); sErver.start (); 

The Server-sent Events specification recommends that if no other data is sent, the keep-alive comments are sent periodically. This allows the proxy server to close the connection if an HTTP connection is inactive for a period of time , so that the proxy server can turn off idle connections to avoid wasting connections on unresponsive HTTP servers. Sending a comment event causes this mechanism to not occur on a valid connection. Although EventSource automatically rebuilds the connection, sending a comment event can prevent unnecessary reconnection.
The Server-sent event is based on the HTTP streaming. As mentioned above, response will always open, and when events occur on the server side, events are written to response. Theoretically, if the network intermediary such as HTTP Proxy does not immediately forward part of the response,http streaming will cause some problems. Now the HTTP RFC (RFC2616 hypertext Transfer protocal–http/1.1) does not require that the portions of the response must be forwarded immediately. However, many of the popular, well-worked web applications that already exist are based on HTTP streaming. Also, product-level mediations often avoid buffering large amounts of data to reduce memory usage.
Unlike other popular coment protocols such as Bayeux and Bosh, the Server-sent event supports only one-way from server to client channels. The Bayeux protocol supports bidirectional communication channels. In addition, Bayeux is able to use HTTP streaming and polling. The Bosh protocol also supports bidirectional communication channels, but Bosh is based on a polling mechanism. (The so-called polling is that the client periodically sends the request to the server to fetch the data).
Although Server-sent events is less powerful than Bayeux and Bosh, the Server-sent events has the potential to become the dominant protocol in situations where only one-way servers are pushed to the client (in many cases). The Server-sent events protocol is much simpler to bayeus and Bosh. In addition, server-sent events is supported by all compatible HTML5 browsers (this is the power of the spec).

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.