YouTip LogoYouTip

Html5 Websocket

# HTML5 WebSocket WebSocket is a protocol that provides full-duplex communication over a single TCP connection, introduced in HTML5. WebSocket simplifies data exchange between client and server, allowing the server to push data to the client proactively. In the WebSocket API, the browser and server only need to perform a single handshake to establish a persistent connection for bidirectional data transfer. In the WebSocket API, the browser and server only need to perform a handshake action, after which a fast channel is formed between them. Data can then be directly transmitted between the two. Currently, many websites use Ajax polling to implement push technology. Polling involves the browser sending HTTP requests to the server at specific intervals (e.g., every 1 second), and the server returns the latest data to the client's browser. This traditional model has a significant drawback: the browser must constantly send requests to the server. However, HTTP requests may contain lengthy headers, with the actual useful data being only a small portion, which obviously wastes a lot of bandwidth and other resources. The WebSocket protocol defined by HTML5 can better save server resources and bandwidth, and enables more real-time communication. !(#) The browser uses JavaScript to send a request to the server to establish a WebSocket connection. Once the connection is established, the client and server can directly exchange data over the TCP connection. After obtaining a WebSocket connection, you can use the **send()** method to send data to the server and the **onmessage** event to receive data returned from the server. The following API is used to create a WebSocket object. var Socket = new WebSocket(url, ); The first parameter, url, specifies the URL to connect to. The second parameter, protocol, is optional and specifies the sub-protocol(s) that are acceptable. * * * ## WebSocket Properties The following are properties of the WebSocket object. Assume we have created a Socket object using the code above: | Property | Description | | --- | --- | | Socket.readyState | The read-only property **readyState** represents the connection state and can have the following values: * 0 - Indicates the connection has not 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 could not be opened. | | Socket.bufferedAmount | The read-only property **bufferedAmount** represents the number of bytes of UTF-8 text that have been queued by send() but not yet transmitted. | * * * ## WebSocket Events The following are events related to the WebSocket object. Assume we have created a Socket object using the code above: | Event | 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 methods related to the WebSocket object. Assume we have created a Socket object using the code above: | Method | Description | | --- | --- | | Socket.send() | Sends data using the connection. | | Socket.close() | Closes 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 is different from a typical HTTP request and includes additional header information. The additional header "Upgrade: WebSocket" indicates that this is an HTTP request for a protocol upgrade. The server parses these additional headers and sends a response back to the client. The WebSocket connection between the client and server is then established, allowing both parties to freely transmit information through this connection channel. This connection remains active until either the client or server actively closes it. ### Client-side HTML and JavaScript Most browsers currently support the WebSocket() interface. You can try the example in the following browsers: Chrome, Mozilla, Opera, and Safari. Content of tutorial_websocket.html file function WebSocketTest() { if ("WebSocket" in window) { alert("Your browser supports WebSocket!"); // Open a web socket var ws = new WebSocket("ws://localhost:9998/echo"); ws.onopen = function() { // WebSocket is connected, send data using send() ws.send("Send data"); alert("Data sent..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("Data received..."); }; ws.onclose = function() { // Close websocket alert("Connection closed..."); }; } else { // The browser doesn't support WebSocket alert("Your browser does not support WebSocket!"); } } * * * ## Installing pywebsocket Before running the above program, we need to create a WebSocket-supporting service. Download mod_pywebsocket from (https://github.com/googlearchive/pywebsocket), or use the git command to download: git clone https://github.com/googlearchive/pywebsocket

mod_pywebsocket requires a Python environment.

mod_pywebsocket is a WebSocket extension for Apache HTTP. The installation steps are as follows:

  • Unzip the downloaded file.

  • Navigate to the pywebsocket directory.

  • Execute the command:

    $ python setup.py build $ sudo python setup.py install*   View documentation:
    
    $ pydoc mod_pywebsocket
    
    ### Starting the Service
    
    Execute the following command in the **pywebsocket/mod_pywebsocket** directory:
    
    $ sudo python standalone.py -p 9998 -w ../example/
    The above command will start a service on port 9998. Use -w to set the directory where the handler echo_wsh.py is located.
    
    Now we can open the previously created tutorial_websocket.html file in the Chrome browser. If your browser supports WebSocket(), click "Run WebSocket", and you will see pop-up windows for each step of the process. The process is demonstrated in the following Gif:
    
    !(#)
    
    After we stop the service, "Connection closed..." will pop up.
← Html5 WebsocketJs Conventions β†’