Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML5 WebSocket

HTML5 WebSocket

WebSocket is a protocol introduced in HTML5 that provides full-duplex communication over a single TCP connection.

WebSocket makes data exchange between the client and server simpler, allowing the server to proactively push data to the client. In the WebSocket API, the browser and server only need to complete one handshake, after which a persistent connection can be created directly between them for bidirectional data transmission.

In the WebSocket API, the browser and server only need to perform a handshake, and then a fast channel is formed between them. Data can be directly transmitted between the two.

Currently, many websites use Ajax polling to implement push technology. Polling means that at specific time intervals (such as every 1 second), the browser sends an HTTP request to the server, which then returns the latest data to the client's browser. This traditional model has obvious drawbacks: the browser must continuously send requests to the server, and HTTP requests may contain long headers while the actually valid data may be only a small part, which clearly wastes a lot of bandwidth and other resources.

The WebSocket protocol defined by HTML5 can better save server resources and bandwidth, and enable more real-time communication.

The browser sends a request to the server via JavaScript to establish a WebSocket connection. Once the connection is established, the client and server can exchange data directly over the TCP connection.

Once you have obtained a WebSocket connection, you can use the send() method to send data to the server, and use the onmessage event to receive data returned by the server.

The following API is used to create a WebSocket object.



var Socket = new WebSocket(url, [protocol] );

The first parameter in the above code, url, specifies the URL of the connection. The second parameter, protocol, is optional and specifies the acceptable sub-protocols.


WebSocket Properties

The following are properties of the WebSocket object. Assume we created the Socket object using the above code:

property Description
Socket.readyState

Read-Only Properties readyState Indicates the connection state, which can be one of the following values:

  • 0 - indicates the connection has not yet been established.

  • 1 - indicates the connection is established and communication is possible.

  • 2 - indicates the connection is in the process of closing.

  • 3 - indicates the connection has been closed or cannot be opened.

  • | | Socket.bufferedAmount |

    Read-Only Properties bufferedAmount The number of UTF-8 text bytes that have been placed in the queue by send() awaiting transmission but have not yet been sent.

    |

    WebSocket Events

    The following are related events of the WebSocket object. Assume we created the Socket object using the above code:

    Events Event handler Description
    open Socket.onopen Triggered when the connection is established
    message Socket.onmessage Triggered when the client receives data from the server
    error Socket.onerror Triggered when a communication error occurs
    close Socket.onclose Triggered when the connection is closed

    WebSocket Methods

    The following are related methods of the WebSocket object. Assume we created the Socket object using the above code:

    Method Description
    Socket.send()

    Send data using the connection

    Socket.close()

    Close the Connection


    WebSocket Example

    The WebSocket protocol is essentially a TCP-based protocol.

    To establish a WebSocket connection, the client browser first sends an HTTP request to the server. This request differs from a normal HTTP request in that it contains some additional header information; the header "Upgrade: WebSocket" indicates that this is an HTTP request applying for a protocol upgrade. The server parses these additional headers and generates a response returned to the client, and the WebSocket connection between client and server is established. Both parties can freely transmit information through this connection channel, and the connection persists until either the client or server actively closes it.

    Client-side HTML and JavaScript

    Currently most browsers support the WebSocket() interface; you can try the example in the following browsers: Chrome, Mozilla, Opera, and Safari.

    Contents of the runoob_websocket.html file

    
    
    
    
    
    
       
    
       
    
       Runoob Tutorial(runoob.com)
    
        
    
          
    
            
    
       
    
       
    
       
    
          
    
          
    
       
    
    
    
    

    Installing pywebsocket

    Before executing the above program, we need to create a service that supports WebSocket. From pywebsocket download mod_pywebsocket, or use the git command to download:

    
    
    git clone https://github.com/googlearchive/pywebsocket
    
    

    mod_pywebsocket 需要 python 环境支持

    mod_pywebsocket 是一个 Apache HTTP 的 Web Socket扩展,安装步骤如下:

    • 解压下载的文件。

    • 进入 pywebsocket 目录。

    • 执行命令:

      $ python setup.py build
      
      $ sudo python setup.py install
      
      
    • See the documentation:

      $ pydoc mod_pywebsocket
    • Start the service

      in pywebsocket/mod_pywebsocket Execute the following command in the directory:

      
      
      $ sudo python standalone.py -p 9998 -w ../example/
      
      

      The above command starts a service on port 9998, using -w to set the directory where the handler script echo_wsh.py is located.

      Now we can open the runoob_websocket.html file we created earlier in the Chrome browser. If your browser supports WebSocket(), click "Run WebSocket" and you will see the pop-up windows for each step of the entire process. The flow is demonstrated in a GIF:

      After we stop the service, a "Connection closed..." message will pop up.