First, WebSocket introduction
WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5.
WebSocket protocol was born in 2008 and became an international standard in 2011. All browsers already support it.
WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. A handshake between the browser and the server is all it takes to create a persistent connection and two-way data transfer.
In the WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.
In order to implement push technology, many websites use Ajax polling. (timer +Ajax), the browser sends HTTP requests to the server, and then the server returns the latest data to the client’s browser. This traditional pattern has obvious disadvantages, namely, the browser needs to make continuous requests to the server. However, HTTP requests may contain long headers, in which only a small portion of the data is really valid, which obviously wastes a lot of bandwidth and other resources.
The WebSocket protocol defined by HTML5 can better save server resources and bandwidth, and can communicate in more real time.
Its biggest characteristic is that the server can take the initiative to push information to the client, the client can also take the initiative to send information to the server, is a real two-way equal dialogue, belongs to a server push technology.
Other features include:
-
Based on TCP protocol, the implementation of the server side is relatively easy.
-
Good compatibility with HTTP, default ports 80 and 443.
-
The data format is relatively light, with low performance overhead and high communication efficiency.
-
You can send text or binary data.
-
There are no same-origin restrictions, and clients can communicate with any server.
-
The protocol identifier is WS (or WSS if encrypted), and the server URL is the URL.
wss://echo.websocket.org
Copy the code
Second, the WebSocket API
-
WebSocket constructor
The WebSocket object is used as a constructor to create a new WebSocket instance.
var Socket = new WebSocket('wss://echo.websocket.org'); Copy the code
After executing the above statement, the client will connect to the server.
-
webSocket.readyState
CONNECTING: The value is 0, indicating that a connection is being established. OPEN: the value is 1, indicating that the connection is successful and communication can be started. CLOSING: A value of 2 indicates that the connection is CLOSING. CLOSED: the value is 3, indicating that the connection is CLOSED or fails to be opened.Copy the code
Here is an example.
switch (Socket.readyState) { case WebSocket.CONNECTING: console.log('Connecting! ') break; case WebSocket.OPEN: console.log('Connection successful! ') break; case WebSocket.CLOSING: console.log('Connection closing! ') break; case WebSocket.CLOSED: console.log('Connection closed! ') break; default: // this never happens break; } Copy the code
-
WebSocket event
The event Event handler describe open Socket.onopen Triggered when the connection is established message Socket.onmessage Triggered when the client receives data from the server error Socket.onerror Triggered when a communication error occurs close Socket.onclose Triggered when the connection is closed The onopen property of the instance object, which specifies the callback function if the connection is successful.
Socket.onopen = function () { console.log('Hello Word! '); }; Copy the code
If you want to specify multiple callback functions, you can use the addEventListener method.
Socket.addEventListener('open'.function (event) { console.log('Hello Word! '); }); Copy the code
-
WebSocket method
methods describe Socket.send() Use the connection to send data Socket.close() Close the connection Example of sending text.
Socket.send('your message'); Copy the code
Example of sending a Blob object.
var file = document.querySelector('input[type="file"]').files[0]; Socket.send(file); Copy the code
Three, WebSocket application
- Instant messaging
- The weather
- Background statistics updated
- Message push (panic buying, SEC kill alert)
- Mall backstage commodity editor is locked
Four, extension,
-
The EventSource server communicates with the client
EventSource is a technical implementation of the Server-Sent Events specification in HTML5. The EventSource interface is used to receive events sent by the server. It connects to a server over HTTP and receives events in text/event-stream format without closing the connection. The EventSource server can actively discover messages to the client, using HTTP protocol, one-way communication, can only be sent by the server to the browser. Compared with WebSocket, it is lightweight and simple to use.
-
Webpack hot update feature
Node communicates with webpack-hot-middleware/middleware.js, and opens webpack-hot-middleware/client.js.
source = new window.EventSource(options.path); source.onopen = handleOnline; source.onerror = handleDisconnect; source.onmessage = handleMessage; Copy the code
After saving the modified file, I found that the console Webpack was recompiled immediately and the UI was updated without refreshing.
1. You will find that the Webpack compiled result contains two more update files and the file name contains the hash information above.
4.73 c528ba5b06e7e9ab26. Hot - update. Js 73 c528ba5b06e7e9ab26. Hot - update. JsonCopy the code
Json is an Ajax request, and hot-update.js is a GET request, which inserts a script link into the document.
3. Insert page content by 4.73 c528ba5b06e7e9ab26. Hot – update. Js script file
After multiple hot updates, you can see that the hash of the EventStrean message sent by the server will be used as the hash of the next hot-update.json and hot-update.js files.