Let’s take a look at the chart below:
You can see that this is a simple chat room, two Windows of the message is sent and received in real time, this is mainly used today we want to talk about websocket implementation.
What is a Websocket?
websocket
It’s a network communication protocol, as we all knowhttp
Agreement,http
Protocols can only be initiated from the client, not pushed from the server to the clientwebsocket
A protocol that not only sends data from the client to the server, but also actively pushes data from the service to the client. Let’s start with a picture:And we can see,http
A request is a loop in which the client initiates a request, the server responds, and then disconnects, the client initiates, and the server responds. whilewebsocket
After the client initiates a connection, the connection is maintained. During this period, both the client and the server can send data to each other until the connection is closed.websocket
Some other features:
(1) Based on THE TCP protocol, the implementation of the server side is relatively easy.
(2) It has good compatibility with HTTP protocol. 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.
(3) The data format is relatively light, the performance overhead is small, and the communication is efficient.
(4) Can send text, can also send binary data.
(5) There is no source restriction, and the client can communicate with any server.
Copy the code
(6) The protocol identifier is
ws
(If encrypted, otherwisewss
), the server URL is the URL.
Application scenarios
Imagine a scenario where we need to implement a payment success and give the user a hint of success. Before the WebSocket protocol was used, people used a polling method. That is, the client periodically sends a request to the server to see if it receives the payment amount. If it does not, it keeps sending and stops when it receives the payment amount. Code similar to the following:
function getIsPaySuccess() {
var timmer = setInterval(function () {
$.ajax({
url: '/getJayStatus'. success: function (res) {
if (res.status) { clearInterval(timmer) } }, fail: function () { } }) }, 1000) } Copy the code
A lot of resources were wasted in sending requests, and the response was not timely because I requested every 1 second and didn’t immediately get a successful payment status. At this point, we need to use the Websocket method. In general, Websockets need to be used in some responsive scenarios.
1. Social subscriptions
Sometimes we need to receive timely subscription messages, such as lottery notifications, online invitations, payment results, etc.
2. Multiplayer games
Many games are co-operative, and player actions and states need to be synchronized to all players in a timely manner.
3. Collaborate on document editing
The editing status of the same document must be synchronized to all participating user interfaces.
4. Data flow status
For example, upload and download files, file progress, file upload success.
5. Chat with multiple people
Many scenarios require multiple participants to participate in the discussion and chat, and messages sent by users need to be synchronized to all users at the first time.
6. Stock virtual currency price
Stock and virtual currency prices are real-time fluctuations, prices are closely related to users’ operations, timely push is of great help to users to follow the market.
Code implementation
We use the following code to explain the creation of a Websocket, the properties it has, the methods it can call, and the events it can listen to:
// Enumeration of connection states
const readyStateMap = {
0: 'Connection not established'. 1: 'Connection established, ready to communicate'. 2: 'Connection closing in progress'. 3: 'Connection closed or connection cannot be opened' } Object.freeze(readyStateMap) class WsTest { constructor(url) { // Create a WebSocket instance. The first parameter is the url of the connection, no cross-domain restrictions, and the second parameter is the acceptable protocol this.ws = new WebSocket(url); // The readyState property, read-only, indicates the connection status console.log(this.ws.readyState, readyStateMap[this.ws.readyState]) BufferedAmount Number of UTF-8 text bytes that have been queued by send() for transmission but have not yet been sent. console.log(this.ws.bufferedAmount) this.initWs() } initWs() { // event onopen, indicating successful connection this.ws.onopen = (a)= > { console.log(this.ws.readyState, readyStateMap[this.ws.readyState]) // method to send a message to the server, transferring a string this.ws.send(JSON.stringify({type: 'connection'})) }; // Event onMessage, indicating that a server message is received this.ws.onmessage = (evt) = > { console.log(evt.data, 'data') const {type, msg} = JSON.parse(evt.data); console.log('Message type:' + type, 'User ID:' + msg) // close the connection this.ws.close() console.log(this.ws.readyState, readyStateMap[this.ws.readyState]) }; // event onclose, which closes the connection, can also be forcibly disconnected from the server, where the connection can be re-initiated this.ws.onclose = (a)= > { console.log(this.ws.readyState, readyStateMap[this.ws.readyState]) }; // Event onError, emitted when communication error occurs this.ws.onerror = (a)= > { console.log(this.ws.readyState, readyStateMap[this.ws.readyState]) }; } } const ws = new WsTest('ws: / / 203.195.156.57:30002') Copy the code
The above code is commented, which should not be hard to seewebsocket
This code can be directly placed inchrome
Console run:
compatibility
You can see that it is supported by almost all browsers.
conclusion
websocket
Is a similarhttp
A communication protocol.websocket
The biggest feature is that clients and servers can send messages to each other.websocket
Widely used in applications that require real-time communication.websocket
There is no homologous restriction, and the performance cost is low, and the communication is efficient.
This article mainly talks about the definition and basic usage of webSocket protocol, next I will combine the chat room at the beginning of this article to implement a specific WebSocket application. Chat room online experience Address: address
Learning is like rowing upstream, not to advance is to fall back, the rapid development of front-end technology, if you don’t keep learning every day, you will not keep up, I will accompany you, every day to push blog, progress with you, I hope you can pay attention to me, the first time to receive the latest article.
Personal official account: