Introduction to WebSocket

WebSocket is a network communication protocol, which is required for many advanced functions.

1. Why do you need WebSocket?


We already have the HTTP protocol, why do we need another protocol? What good does it bring?

Answer: Because the HTTP protocol has a defect: communication can only be initiated by the client

For example, if we want to know today's weather, only the client sends a request to the server, and the server returns the query result. The HTTP protocol cannot allow the server to actively push information to the client.

The characteristics of this one-way request are destined to be very troublesome for the client to know if the server has continuous state changes. We can only use "polling" : every once in a while, a query is sent to see if the server has new information. The most typical scenario is the chat room.

Polling is inefficient and wastes resources (since the connection must be kept open, or the HTTP connection is always open). Therefore, engineers have been thinking, is there a better way. That's how WebSocket was invented.

What does polling mean?

Polling is a way for the CPU to decide how to provide peripheral device services, also known as "programmed I/O". The concept of the polling method is: the CPU sends out inquiries at regular intervals, and asks each peripheral device in sequence whether it needs its services, and provides services as soon as they are available, and then asks the next peripheral device after the service is over, and then repeats itself continuously.

2. Introduction


The WebSocket protocol was born in 2008 and became an international standard in 2011. All browsers already support it.

Its biggest feature is that the server can actively push information to the client, and the client can also actively send information to the server. It is a real two-way equal dialogue and belongs to a kind of server push technology .

Its features mainly include:

(1) Based on the TCP protocol, the server-side implementation is relatively easy.

(2) It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses the HTTP protocol, so it is not easy to shield during the handshake, and can pass through various HTTP proxy servers.

(3) The data format is relatively light, the performance overhead is small, and the communication is efficient.

(4) Text or binary data can be sent.

(5) There is no same-origin restriction, and the client can communicate with any server.

(6) The protocol identifier is ws (or wss if encrypted), and the server URL is the URL.

create a websocket

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.");

};

4.1 WebSocket constructor


The WebSocket object is used as a constructor to create a new WebSocket instance .

var ws =newWebSocket('ws://localhost:8080');

After executing the above statement, the client will connect to the server.

For a list of all properties and methods of instance objects, see here .

4.2 webSocket.readyState


The readyState attribute returns the current state of the instance object, and there are four types.

CONNECTING: The value is 0, indicating that it is connecting.
OPEN: The value is 1, indicating that the connection is successful and communication is possible.
CLOSING: A value of 2 indicates that the connection is being closed.
CLOSED: The value is 3, indicating that the connection has been closed, or failed to open the connection.

Below is an example.

switch (ws.readyState){
  case WebSocket.CONNECTING: // do something
break;
  case WebSocket.OPEN: // do something
break;
  case WebSocket.CLOSING: // do something
break;
  case WebSocket.CLOSED: // do something
break;
  default: // this never happens
break;}

4.3 webSocket.onopen


The onopen attribute of the instance object is used to specify the callback function after the connection is successful.

ws.onopen =function(){ ws.send('Hello Server!');}

If you want to specify multiple callback functions, you can use the addEventListener method.

ws.addEventListener('open',function(event){ ws.send('Hello Server!');});

4.4 webSocket.onclose


The onclose attribute of the instance object is used to specify the callback function after the connection is closed.

ws.onclose =function(event){var code = event.code;var reason = event.reason;var wasClean = event.wasClean; // handle close event }; ws.addEventListener("close",function(event){var code = event.code;var reason = event.reason;var wasClean = event.wasClean; // handle close event });

4.5 webSocket.onmessage


The onmessage attribute of the instance object is used to specify the callback function after receiving the server data.

ws.onmessage = function(event){var data = event.data; // process data}; ws.addEventListener("message", function(event){var data = event.data; // process data});

Guess you like

Origin blog.csdn.net/weixin_47039061/article/details/128946496