YouTip LogoYouTip

Html5 Websocket

# HTML5 WebSocket WebSocket is a protocol that provides full-duplex communication over a single TCP connection, introduced with HTML5. WebSocket simplifies data exchange between clients and servers, allowing the server to push data to the client proactively. In the WebSocket API, the browser and server only need to complete a handshake once, after which they can create a persistent connection and perform bidirectional data transfer. In the WebSocket API, the browser and server only need to perform a handshake action, 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 involves the browser sending HTTP requests to the server at specific time intervals (e.g., every 1 second), and the server returns the latest data to the client's browser. This traditional pattern has a significant drawback: the browser must constantly send requests to the server. However, HTTP requests may contain long headers, where the actual useful data might be 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 enable more real-time communication. !(#) The browser sends a request to the server to establish a WebSocket connection via JavaScript. 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 receive data returned from the server via the **onmessage** event. The following API is used to create a WebSocket object. var Socket = new WebSocket(url, ); The first parameter `url` in the above code specifies the URL to connect to. The second parameter `protocol` is optional and specifies the acceptable sub-protocol. * * * ## WebSocket Properties The following are the properties of the WebSocket object. Assume we have created a Socket object using the above code: | Property | Description | | --- | --- | | Socket.readyState | The read-only property **readyState** represents the connection state, which can be one of 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 the connection could not be opened. | | Socket.bufferedAmount | The read-only property **bufferedAmount** is the number of bytes of UTF-8 text that have been queued by send() but not yet transmitted. | * * * ## WebSocket Events The following are the events related to the WebSocket object. Assume we have created a Socket object using the above code: | 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 the methods related to the WebSocket object. Assume we have created a Socket object using the above code: | 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 contains some additional header information. The additional header "Upgrade: WebSocket" indicates that this is an HTTP request requesting 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, and both parties can freely transmit information through this connection channel. This connection will persist 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 doesn't support WebSocket!"); } } * * * ## Installing pywebsocket Before executing 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.

  • Enter 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 entire process. The process is demonstrated in the following GIF:
    
    !(#)
    
    After we stop the service, "Connection closed..." will pop up.
← Php Coalescing OperatorHtml5 Websocket β†’