HTML 5 WebSocket

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

WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be carried out.

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

Nowadays, in order to implement push technology, many websites use Ajax polling. Polling is at a specific time interval (such as every 1 second), the browser sends an HTTP request to the server, and then the server returns the latest data to the client’s browser. This traditional mode brings obvious shortcomings, that is, the browser needs to continuously send requests to the server, but the HTTP request may contain a long header, and the really valid data may be only a small part, which is obviously wasteful. A lot of bandwidth and other resources.

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

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

After you get 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 , [ protocol ] );      

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

WebSocket properties

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

Attributes description
Socket.readyState

The read-only attribute readyState represents the connection state, which can be the following values:

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

  • 1-Indicates that the connection has been 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

The read-only attribute bufferedAmount has been put into the queue waiting for transmission by send(), but the number of UTF-8 text bytes that have not been sent.

WebSocket events

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

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

WebSocket method

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

method description
Socket.send()

Use connection to send data

Socket.close()

Close the connection

WebSocket instance

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 a normal HTTP request and contains some additional header information. The additional header information “Upgrade: WebSocket” indicates that this is an application protocol. For the upgraded HTTP request, the server parses these additional header information and then generates a response message to return to the client. The WebSocket connection between the client and the server is established, and the two parties can freely transmit information through this connection channel, and the connection will be Continue to exist until either the client or the server actively closes the connection.

HTML and JavaScript on the client side

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

runoob_websocket.html file content

<!DOCTYPE HTML> 
<html> 
	<head> 
		<meta charset = "utf-8" > 
		<title> Novice Tutorial</title>
		<script type = "text/javascript"> 
			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 () { 
						// Web Socket is connected, use the send() method to send data 
						ws.send ( "Sending data" ); 
						alert ( "Data sending..." ); 
					}; 
					ws.onmessage = function(evt) { 
						var received_msg = evt . data ; 
						alert ( "Data received..." ); 
					};   
					ws . onclose = function () { 
						// Close websocket 
						alert ( "The connection is closed..." ); 
					}; 
				} 
				else { 
					// The browser does not support WebSocket 
					alert ( "Your browser does not support WebSocket!" ); 
				} 
			} 
		</script>
  </head> 
	<body>
		<div id = " sse " > 
			<a href = "javascript:WebSocketTest()"> Run WebSocket </a> 
		</div> 
	</body> 
</html>

Install pywebsocket

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

HTTPS clone Git : //github.com/googlearchive/pywebsocket <P> 
mod_pywebsocket   need python environment supports </ P > 
mod_pywebsocket is the Apache the HTTP to the Web the Socket extension steps are as follows: </ P >
   

<ul> <li><p> Unzip the downloaded file. < /p></ li > <li><p> Enter the <b> pywebsocket < /b> directory. </ p ></ li > <li><p> Execute command:</ p > <pre> $ python setup . py build


$ sudo python setup . py install

View the documentation description:

$ pydoc mod_pywebsocket

Open service

Execute the following commands in the pywebsocket/mod_pywebsocket directory:

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

The above command will start a service with a port number of 9998. Use -w to set the directory where the handler echo_wsh.py is located.

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

After we stop the service, it will pop up “connection closed…”.

Receive Server-Sent event notification

The EventSource object is used to receive event notifications sent by the server: