Home >Web Front-end >H5 Tutorial >A brief analysis of HTML5's WebSocket and server push events_html5 tutorial skills

A brief analysis of HTML5's WebSocket and server push events_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:45:541917browse

WebSockets

Web Sockets is a new generation of two-way communication technology for web applications, running on a single socket, which is exposed in HTML5-compatible browsers through a JavaScript interface.

Once you have obtained the Web Socket connection on the web server, you can send data from the browser to the server by calling the send() method, and receive data from the server to the browser through the onmessage event handler.

The following is the API to create a new WebSocket object.

JavaScript CodeCopy content to clipboard
  1. var Socket = new WebSocket(url, [protocal] );

The first parameter url is used to specify the URL to connect to. The second attribute - port is optional and, if provided, specifies a subprotocol that the server must support for a successful connection.

WebSocket Properties
The following are the properties of the WebSocket object. Assume we have created the above Socket object:

Attribute Description
Socket.readyState
属性 描述
Socket.readyState

只读属性readyState表示连接的状态。有以下取值:

  1. 0 表示连接尚未建立。

  2. 1 表示连接已建立,可以进行通信。

  3. 2 表示连接正在进行关闭握手。

  4. 3 表示连接已经关闭或者连接不能打开。

Socket.bufferedAmount

只读属性bufferedAmount表示已经使用 send() 方法排队的 URF-8 文本字节数。

Read-only attribute
readyState represents the status of the connection. It has the following values:
0 means the connection has not been established yet.
事件 事件处理程序 描述
open Socket.onopen 建立 socket 连接时触发这个事件。
message Socket.onmessage 客户端从服务器接收数据时触发。
error Socket.onerror 连接发生错误时触发。
close Socket.onclose 连接被关闭时触发。

  • 1 means the connection is established and communication is possible.
  • 2 indicates that the connection is undergoing a closing handshake.
    方法 描述
    Socket.send()

    send(data) 方法使用连接传输数据。

    Socket.close()

    close() 方法用于终止任何现有连接。

  • 3 means the connection has been closed or the connection cannot be opened.
  • Socket.bufferedAmount Read-only attributebufferedAmountRepresents the number of URF-8 text bytes that have been queued using the send() method.
    WebSocket Events The following are events related to the WebSocket object. Assume we have created the above Socket object: WebSocket methods The following are the methods related to the WebSocket object. Assume we have created the above Socket object:
    Method Description
    Socket.send() The send(data) method uses a connection to transfer data.
    Socket.close() The close() method is used to terminate any existing connection.

    Server Push Events
    Traditional web applications generate events that are sent to the web server side. For example, clicking a link will request a new page from the server.

    This type of time from the web browser to the web server can be called a client-side event.

    With the advent of HTML5, WHATWG Web Applications 1.0 introduced an event stream from the web server to the web browser called Server Push Events (SSE). Use SSE to continuously push DOM events to the user's browser.

    This event streaming method will open a persistent connection to the server and send data to the client when new messages are available, eliminating the need for continuous polling.

    SSE Web Application
    To use server push events in a web application, we need to add an element to the document.

    The src attribute of the

    element should point to a URL that should provide an HTTP persistent connection for sending a data stream containing the event.

    This URL will point to a PHP, PERL or any Python script that continuously sends event data. Here is a simple example of a web application that expects the server time.

    XML/HTML CodeCopy content to clipboard
    1. >
    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-side script
    Server-side script should send Content-type header specifying the type as text/event-stream, as shown below:


    Copy code
    The code is as follows:
    print "Content-Type: text/event-streamnn" ;

    After setting the Content-type, the server-side script will send an Event: tag followed by the event name. The following example will send a newline-terminated Server-Time as the event name.


    Copy code
    The code is as follows:
    print "Event: server-timen";

    The last step is to send the event data using the Data: tag, followed by the integer string value terminated with a newline, like this:


    Copy code
    The code is as follows:
    $time = localtime();
    print " Data: $timen";

    The following is the complete ticker.cgi written in perl:


    Copy code
    The code is as follows:

    #!/usr/bin/perl
    print "Content-Type: text/event-streamnn";
    while(true){
    print "Event: server-timen";
    $time = localtime();
    print " Data: $timen";
    sleep(5);

    Handling server push events
    Let’s modify our web application to handle server push events. Here is the final example:

    XML/HTML CodeCopy content to clipboard
    1. >  
    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.    }   
    13. script>  
    14. head>  
    15. <body>  
    16. <div id="sse">  
    17.    <eventsource src="/cgi-bin/ticker.cgi" />  
    18. div>  
    19. <div id="ticker" name="ticker">  
    20.    [TIME]   
    21. div>  
    22. body>  
    23. html>  

    在测试服务器推送事件之前,建议你确保你的 Web 浏览器支持这一概念。

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn