HTML5 WebSocket


WebSocket is a protocol for full-duplex communication on a single TCP connection that HTML5 began to provide.

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

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

After you obtain the Web Socket connection, you can send data to the server through the send() method, and receive the data returned by the server through the onmessage event.

The following API is used to create WebSocket objects.

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

The first parameter url in the above code specifies the URL of the connection. The second parameter protocol is optional and specifies acceptable subprotocols.


WebSocket Properties

The following are the properties of the WebSocket object. Suppose we use the above code to create a Socket object:

PropertiesDescription
Socket.readyState

Read-only attributereadyState Indicates the connection status, which can be the following values:

  • 0 - Indicates that the connection has not yet been established.

  • 1 - Indicates that the connection is established and communication is possible.

  • 2 - Indicates that the connection is being closed.

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

Socket.bufferedAmount

Read-only propertybufferedAmount has been put in by send() The number of bytes of UTF-8 text that are queued for transmission but have not yet been sent.


WebSocket Events

The following are related events of the WebSocket object. Suppose we use the above code to create a Socket object:

##messageSocket.onmessageTriggered when the client receives server data##errorclose
EventEvent handlerDescription
openSocket.onopenTriggered when connection is established
Socket.onerrorTriggered when a communication error occurs
Socket.oncloseTriggered when the connection is closed
WebSocket method

The following are the relevant methods of the WebSocket object. Suppose we use the above code to create a Socket object:

MethodSocket.send( )Use the connection to send dataSocket.close()Close the connection

WebSocket Example

The WebSocket protocol is essentially a TCP-based protocol.

In order to establish a WebSocket connection, the client browser must first initiate an HTTP request to the server. This request is different from the usual HTTP request and contains some additional header information, including the additional header information "Upgrade: WebSocket" Indicates that this is an HTTP request to apply for a protocol upgrade. The server parses these additional header information and then generates response information and returns it to the client. The WebSocket connection between the client and the server is established, and both parties can communicate freely through this connection channel. information, and this connection will continue to exist until either the client or the server actively closes the connection.

Client-side HTML and JavaScript

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

php_websocket.html File content

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>php中文网(php.cn)</title>
	
      <script type="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in window)
            {
               alert("您的浏览器支持 WebSocket!");
               
               // 打开一个 web socket
               var ws = new WebSocket("ws://localhost:9998/echo");
				
               ws.onopen = function()
               {
                  // Web Socket 已连接上,使用 send() 方法发送数据
                  ws.send("发送数据");
                  alert("数据发送中...");
               };
				
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  alert("数据已接收...");
               };
				
               ws.onclose = function()
               { 
                  // 关闭 websocket
                  alert("连接已关闭..."); 
               };
            }
            
            else
            {
               // 浏览器不支持 WebSocket
               alert("您的浏览器不支持 WebSocket!");
            }
         }
      </script>
		
   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
      
   </body>
</html>

Installation pywebsocket

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

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

mod_pywebsocket requires python environment support

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


  • Unzip the downloaded file.

  • Enter the pywebsocket directory.

  • Execute command:

    $ python setup.py build
    $ sudo python setup.py install
  • View document description:

    $ pydoc mod_pywebsocket

Start service

Execute the following command in the pywebsocket/mod_pywebsocket directory:

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

The above command will open a service with port number 9998, use -w to set the handler echo_wsh.py Table of contents.

Now we can open the php_websocket.html file created earlier in the Chrome browser.


Description