Get to know WebSocket

Get to know WebSocket

1. What is WebSocket?

In order to solve the problem of frequent establishment of link disconnection (TCP link) in http communication and to realize the function of server push, WebSocket was born.

In the http1.X version, the request can only be processed by the client initiated and the server responded, and the server cannot actively push (HTTP2.0 implements server push).

Second, the characteristics of WebSocket

  • Built on top of TCP link
  • Good compatibility with HTTP protocol, use HTTP protocol in the handshake phase
  • The data format is relatively lightweight, with low overhead and efficient communication
  • There is no homology restriction, and it can communicate with any server
  • You can send text or binary data
  • Server-side push is possible

Three, simple to use

var ws = new WebSocket("wss://echo.websocket.org");

ws.onopen = function(evt) {
    
     
  console.log("Connection open ..."); 
  ws.send("Hello WebSockets!");
};

ws.onmessage = function(evt) {
    
    
  console.log( "Received Message: " + evt.data);
  ws.close();
};

ws.onclose = function(evt) {
    
    
  console.log("Connection closed.");
};  

Reference blog post: http://www.ruanyifeng.com/blog/2017/05/websocket.html

Guess you like

Origin blog.csdn.net/wdhxs/article/details/114584895