Keep updating ing

WebSocket

What is the WebSocket

WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5. Yes, WebSocket is a protocol, like HTTP, HTTPS, etc., so we need to know that first.

Let’s compare the HTTP protocol:

The characteristics of the WebSocket

1. He communicates both ways.

2, better binary support, in addition to sending text, can also send binary data.

3. Also based on TCP.

4, with HTTP protocol has good compatibility. 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.

Why WebSocket

I always think that when we learn something new, it’s important to know why it’s there.

So if there is HTTP, why WebSocket?

Because HTTP protocol communication can only be initiated by the client, that is, one-way request, and we in real life, will need the server to push messages to the client.

If we need to get some information whether there is an update, we can only use the method of “polling” to the server request, it is conceivable that this way will cause continuous requests to send, waste resources. So you have websockets for two-way communication.

How to use WebSocket

The client

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."); };Copy the code

How do I apply for the WS protocol upgrade

The client

We can reuse HTTP when using WebSocket, but we need to make a change in the request header:

GET/HTTP/1.1 Host: localhost:8080 Origin: http://127.0.0.1:3001 Connection: Upgrade Upgrade: websocket Sec-WebSocket-Version: 12Copy the code

Connection: Upgrade indicates that the protocol is to be upgraded.

Upgrade: websocket: indicates that the websocket protocol is to be upgraded.

Sec-websocket-version: indicates the WebSocket Version.

Refer to the article

WebSocket: 5 minutes from beginner to master

I think the author wrote well, but due to my lack of knowledge, I only wrote what I understood. You need to continue to learn about this. So this article can only serve as a learning record…..