English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 WebSocket

WebSocket is an HTML5 A protocol that provides full-duplex communication on a single TCP connection.


WebSocket makes the data exchange between the client and server simpler, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete one handshake, directly create a persistent connection between them, and perform bidirectional data transmission.

In the WebSocket API, the browser and server only need to make a handshake, and then, a fast channel is formed between the browser and the server. Data can be directly exchanged between them.

Now, many websites use Ajax polling technology to implement push technology. Polling is at specific time intervals (such as every1seconds), the browser sends an HTTP request to the server, and then the server returns the latest data to the browser of the client. This traditional model has obvious disadvantages, that is, the browser needs to continuously send requests to the server, however, the HTTP request may contain a relatively long header, of which the truly effective data may only be a small part, which is obviously a waste of a lot of bandwidth and other resources.

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

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

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

The following API is used to create a WebSocket object.

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

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

WebSocket Properties

The following are the properties of the WebSocket object. Assuming we have created a Socket object using the above code:

PropertyDescription
Socket.readyState

Read-only property readyState Indicates the connection state, which can be one of the following values:

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

  • 1 - Indicates that the connection has been established and communication can be performed.

  • 2 - Indicates that the connection is in the process of closing.

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

Socket.bufferedAmount

Read-only property bufferedAmount UTF that has been put into the queue by send() and is waiting to be transmitted but has not been sent yet-8 Text byte count.

WebSocket Events

The following are the relevant events of the WebSocket object. Assuming we have created a Socket object using the above code:

EventEvent HandlerDescription
openSocket.onopenTriggered when the connection is established
messageSocket.onmessageTriggered when the client receives data from the server
errorSocket.onerrorTriggered when an error occurs in communication
closeSocket.oncloseTriggered when the connection is closed

WebSocket Methods

The following are the relevant methods of the WebSocket object. Assuming we have created a Socket object using the above code:

MethodDescription
Socket.send()

Use Connection to Send Data

Socket.close()

Close Connection

WebSocket Example

The WebSocket protocol is essentially a protocol based on TCP.

To establish a WebSocket connection, the client browser must first send an HTTP request to the server. This request is different from a typical HTTP request as it includes some additional header information. The additional header information "Upgrade: WebSocket" indicates that this is a request for protocol upgrade. The server parses these additional headers and then generates a response message to send back to the client. The WebSocket connection between the client and server is established, and both parties can freely transmit information through this connection channel. This connection will persist until either the client or the server actively closes the connection.

Client-side HTML and JavaScript

Most web browsers support the WebSocket() interface, you can try the example in the following browsers: Chrome, Mozilla, Opera, and Safari.

w3codebox_websocket.html file content

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>WebSocket 使用方法,基础教程网(oldtoolbag.com)</title>
    
      <script type="text/javascript">
         function WebSocketTest()
         {
         var x = document.getElementById("websocket");
            if ("WebSocket" in window)
            {
               x.innerHTML="您的浏览器支持 WebSocket!";
               
               // 打开一个 web socket
               var ws = new WebSocket("ws://echo.websocket.org");
                
               ws.onopen = function()
               {
                  // Web Socket 已连接上,使用 send() 方法发送数据
                  ws.send("发送数据");
                  x.innerHTML="数据发送中...";
               };
                
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  x.innerHTML="数据已接收,基础教程(oldtoolbag.com)...";
               };
                
               ws.onclose = function()
               { 
                  // 关闭 websocket
                  x.innerHTML="连接已关闭..."; 
               };
            }
            
            else
            {
               // 浏览器不支持 WebSocket
               x.innerHTML="您的浏览器不支持 WebSocket!";
            }
         }
      </script>
        
   </head>
   <body>
       
      <div id="sse">
         <input type="button" onclick="WebSocketTest()" value="运行 WebSocket">
      </div>
      <div id="websocket"></div>
      
   </body>
</html>
Test and see ‹/›

The test results are shown in the figure below:

The difference between WebSocket and Socket

Software communication has a seven-layer structure, the lower three layers are biased towards data communication, the upper three layers are more biased towards data processing, and the middle transport layer is a bridge between the upper and lower layers, each layer does different work, and upper layer protocols depend on lower layer protocols. Based on the concept of this communication structure.
Socket is actually not a protocol, it is an application layer and TCP/The IP protocol suite is a middle software abstraction layer for communication, which is a set of interfaces. When two hosts communicate, it allows Socket to organize data to comply with the specified protocol. TCP connections are more reliant on the underlying IP protocol, while IP protocol connections depend on the link layer and lower levels.
WebSocket is a typical application layer protocol.

  • Socket is a transport layer protocol

  • WebSocket is an application layer protocol