Learn from the past - WebSocket Tutorial

1. Why do you need WebSocket?

Anyone who is new to WebSockets asks the same question: we already have the HTTP protocol, why do we need another protocol? What benefits can it bring?

The answer is simple, because the HTTP protocol has a flaw: communication can only be initiated by the client.

For example, if we want to know today's weather, we can only make a request from the client 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 (because you have to keep connecting, or the HTTP connection is always open). Therefore, engineers have been thinking, is there a better way. That's how WebSocket was invented.

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.

 

Other features include:

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

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

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

(4) Text can be sent, and binary data can also be sent.

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

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


ws://example.com:80/some/path

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324924686&siteId=291194637