Latest web development tutorials

HTML5 WebSocket

HTML5 WebSocket is a start provided by the full-duplex communication over a single TCP connection protocol.

In the WebSocket API, the browser and the server just to do a handshake action, then, between the browser and the server on the formation of a fast-track. You can transfer data directly between each other.

Browser sends to the server via JavaScript request to establish a WebSocket connection, the connection is established, the client and the server can be connected directly to exchange data via TCP.

When you get the Web Socket connection, you can send data to the server through thesend () method, and to receive the data returned by the server onmessageevent.

The following WebSocket API is used to create objects.

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

The above code first parameter url, specify the URL connection. The second parameter is optional protocol that specifies acceptable sub-protocol.


WebSocket property

These are the attributes WebSocket object. Suppose we use the above code to create a Socket object:

Attributes description
Socket.readyState

Read-only attributereadyState indicates connection status can have the following values:

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

  • 1 - indicates the connection is established, it can communicate.

  • 2 - indicates that the connection being closed.

  • 3 - indicates that the connection has been closed or the connection can not be opened.

Socket.bufferedAmount

Read-only attributebufferedAmount has been send () are placed in a queue waiting for transfer, but has not yet issued a UTF-8 text bytes.


WebSocket event

Here are the events WebSocket object. Suppose we use the above code to create a Socket object:

event Event handler description
open Socket.onopen Triggered when the connection is established
message Socket.onmessage When the client receives the trigger server data
error Socket.onerror It is triggered when an error occurs Communication
close Socket.onclose Triggered when the connection closed

WebSocket method

Here are the methods WebSocket object. Suppose we use the above code to create a Socket object:

method description
Socket.send ()

Use the connection to send data

Socket.close ()

Close connection


WebSocket instance

Nature WebSocket protocol is a TCP-based protocol.

In order to establish a WebSocket connection, the client browser initiates an HTTP server would first like to request that this request and the usual HTTP requests, contains some additional header information, wherein the additional header information "Upgrade: WebSocket" indicates that this is a application protocol upgrade HTTP request, the server parses the additional header information is then generated response message back to the client, WebSocket connection client and server is established, both sides can, through the connecting channel free transmission of information, and this connection It persists until the client or server-side active party to close the connection.

Client HTML and JavaScript

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

w3big_websocket.html file contents

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>本教程(w3big.com)</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 support WebSocket service. From pywebsocket download mod_pywebsocket, or use git command to download:

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

mod_pywebsocket support needed python environment

mod_pywebsocket of an Apache HTTP Web Socket extensions, installation steps are as follows:

  • Unzip the downloaded file.

  • Enterpywebsocket directory.

  • Excuting an order:

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

    $ pydoc mod_pywebsocket

Open Service

Execute the following command inpywebsocket / mod_pywebsocket directory:

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

The above command will open a service port number 9998, use the -w to set the directory handler echo_wsh.py located.

Now we can open w3big_websocket.html file you created earlier in the Chrome browser. If your browser supports WebSocket (), click "Run WebSocket", you can see the entire process each step of the pop-up window, the process Gif demo:

Once we stop the service, it will pop up "Connection closed ...."