Analysis of HTML5 WebSocket and server push events, html5websocket

Source: Internet
Author: User

Analysis of HTML5 WebSocket and server push events, html5websocket


Web Sockets is a new-generation bidirectional communication technology used for Web applications. It runs on a single socket and is exposed to HTML5 compatible browsers through JavaScript interfaces.

Once the Web Socket connection on the Web server is obtained, you can call the send () method to send data from the browser to the server, and use the onmessage event handler to receive data from the server to the browser.

The following is an API for creating a new WebSocket object.

Copy the content to the clipboard using JavaScript Code
  1. Var Socket = new WebSocket (url, [protocal]);

The first parameter url is used to specify the URL to be connected. The second property-port is optional. If it is provided, a server must support successfully connected sub-protocols.

WebSocket attributes
The following describes the attributes of a WebSocket object. Suppose we have created the above Socket object:

Attribute Description
Socket. readyState

Read-only attributeReadyStateIndicates the connection status. Optional values:

  1. 0 indicates that the connection has not been established.

  2. 1 indicates that the connection has been established and communication can be performed.

  3. 2 indicates that the handshake is being closed.

  4. 3 indicates that the connection is closed or the connection cannot be opened.

Socket. bufferedAmount

Read-only attributeBufferedAmountNumber of URF-8 text bytes that have been queued using the send () method.

WebSocket event
The following are WebSocket object-related events. Suppose we have created the above Socket object:
Event Event Handler Description
Open Socket. onopen This event is triggered when a socket connection is established.
Message Socket. onmessage Triggered when the client receives data from the server.
Error Socket. onerror Triggered when a connection error occurs.
Close Socket. onclose Triggered when the connection is closed.

WebSocket Method
The following describes the methods related to WebSocket objects. Suppose we have created the above Socket object:
Method Description
Socket. send ()

The send (data) method uses a connection to transmit data.

Socket. close ()

The close () method is used to terminate any existing connection.

Server push event
Traditional Web applications generate events sent to Web servers. For example, clicking a link will request a new page from the server.

This time type from Web browser to Web Server can be called a customer event.

As HTML5 emerged, WHATWG Web Applications 1.0 introduced an event stream from the Web server to the Web browser, called server push event (SSE ). With SSE, You can continuously push DOM events to your browser.

This event stream method opens a persistent connection to the server, and sends data to the client when new messages are available, so that continuous polling is not required.

SSE Web Application
To use server push events in Web applications, we need to add a <eventsource> element to the document.

The <eventsource> element's src attribute should point to a URL that provides an HTTP persistent connection to send data streams containing events.

This URL points to a PHP, PERL, or any Python script that continuously sends event data. The following is a simple example of a Web application that expects to get the server time.

Copy XML/HTML Code to clipboard
  1. <! Doctype html>
  2. <Html>
  3. <Head>
  4. <Script type = "text/javascript">
  5. /* Define event handling logic here */
  6. </Script>
  7. </Head>
  8. <Body>
  9. <Div id = "sse">
  10. <Eventsource src = "/cgi-bin/ticker. cgi"/>
  11. </Div>
  12. <Div id = "ticker">
  13. <TIME>
  14. </Div>
  15. </Body>
  16. </Html>

SSE server script
The server-side script should send the Content-type header to specify the text/event-stream type, as shown below:

The Code is as follows: print "Content-Type: text/event-stream \ n ";
After Content-type is set, the server script sends an Event: Tag followed by the Event name. In the following example, a Server-Time ending with a linefeed is sent as the event name.

The Code is as follows: print "Event: server-time \ n ";
The last step is to use Data: Label to send event Data, followed by an integer string value ending with a line break, as shown below:

The Code is as follows: $ time = localtime ();
Print "Data: $ time \ n ";
The following is a complete ticker. cgi written in perl:

The Code is as follows:
#! /Usr/bin/perl
Print "Content-Type: text/event-stream \ n ";
While (true ){
Print "Event: server-time \ n ";
$ Time = localtime ();
Print "Data: $ time \ n ";
Sleep (5 );

Handle server push events
Let's modify our Web application to process the server push time. The following is the final example:

Copy XML/HTML Code to clipboard
  1. <! Doctype html>
  2. <Html>
  3. <Head>
  4. <Script type = "text/javascript">
  5. Document. getElementsByTagName ("eventsource") [0].
  6. AddEventListener ("server-time", eventHandler, false );
  7. Function eventHandler (event)
  8. {
  9. // Alert time sent by the server
  10. Document. querySelector ('# ticker'). innerHTML = event. data;
  11. }
  12. </Script>
  13. </Head>
  14. <Body>
  15. <Div id = "sse">
  16. <Eventsource src = "/cgi-bin/ticker. cgi"/>
  17. </Div>
  18. <Div id = "ticker" name = "ticker">
  19. [TIME]
  20. </Div>
  21. </Body>
  22. </Html>

Before testing server push events, we recommend that you make sure your Web browser supports this concept.

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: 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.