preface

People who are new to WebSocket ask the same question: Why do we need another protocol when we already have HTTP? What good can it do?

The simple answer is that HTTP has a flaw: it does not allow the server to actively push information to the client.

In one scheme, after the client initiates a request to establish a connection, the server and the client agree to establish a long connection. The server will hold the connection tightly and send the message to the server, but it has to re-establish the connection after the timeout. This only reduces the number of times the client initiates a request, but does not enable the server to actively connect to the client and send a packet.

What is the WebSocket protocol

WebSocket protocol is born to make: the server can actively push information to the client

What is a Socket?

Two applications (processes) on a network need to communicate with each other in full duplex (full duplex means that both parties can send messages to each other at the same time). The Socket is used to provide end-to-end communication

The essence of a Socket is a special file. Some Socket functions perform operations on it (read/write IO, open/close).

In this way, we can build a desktop IM application that lets users on different hosts send messages. In essence, Socket is not a new protocol, it is only for programmers to facilitate network programming and TCP/IP protocol family communication mechanism of an encapsulation

Advantages of WebSocket:

(1) Based on THE TCP protocol, the implementation of the server side is relatively easy. (2) It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers. (3) The data format is relatively light, the performance overhead is small, and the communication is efficient. (4) Can send text, can also send binary data. (5) There is no source restriction, and the client can communicate with any server. (6) Full duplex, so the server can actively send data to the client at any time. (7) The protocol identifier is WS (or WSS if encrypted), and the server URL is the URL

The core of the WebSocket

WebSocket establishes a connection through TCP (the client notifies the server of the need to use WebSocket for data transmission). After the connection is established, WebSocket is used for communication

The protocol is full-duplex, so the server can proactively send data to the client at any time

WebSocket creation and use

The following APIS are used to create WebSocket objects.

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

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

The properties of the WebSocket

WebSocket event

The method of WebSocket

Example of WebSocket

<! DOCTYPEHTML>
<html>
   <head>
     <meta charset="utf-8">
     <title>Use of the WebSocket protocol</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(){
                  // The Web Socket is connected, use the send() method to send data
                  ws.send("Send data");
                  alert("Data in transit...");
               };
                
               ws.onmessage = function (evt){ 
                  var received_msg = evt.data;
                  alert("Data received...");
               };
                
               ws.onclose = function(){ 
                  / / close the websocket
                  alert("Connection closed..."); 
               };
            }
            
            else alert("Your browser does not support WebSocket!");
         }
      </script>
   </head>
   <body>
      <div id="sse">
         <a href="javascript:WebSocketTest()">Run the WebSocket</a>
      </div>
   </body>
</html>
Copy the code

Send and receive binary data using WebSocket

WebSocket can send or receive binary data through an ArrayBuffer.

var socket = new WebSocket('ws: / / 127.0.0.1:8081'); / / fill in the url
socket.binaryType = 'arraybuffer';

// Listen for the socket to open
socket.addEventListener('open'.function (event) {
  // Send binary data
  var typedArray = new Uint8Array(4);
  socket.send(typedArray.buffer);
});

// Receive binary data
socket.addEventListener('message'.function (event) {
  var arrayBuffer = event.data;
  // Do some processing
});
Copy the code

The disadvantage of the WebSocket

Not compatible with older browsers

Refer to the article

  • WebSocket – Baidu Encyclopedia
  • Websocket(I) – principles and basic properties and methods
  • Reference | MDN WebSocket – Web API interface