What is a WebSocket?
WebSocket is a protocol for full duplex communication over a single TCP connection.Here we find an interesting word:'Full duplex', so let's get a simple idea of how to communicate!
Single Work
In both sides of communication, one party is fixed as the sender and the other as the receiver.Information can only be transmitted in one direction.
For example, communication between a computer and a printer is a one-way mode
To put it simply: I hit you and you can only bear it!
Half duplex
Allows data to be transmitted in two directions, but data can only be transmitted in one direction at the same time, which is actually a switching unit.
For example, HTTP protocol: the client sends a request to the server (one-way), and the server responds to the request (one-way)
Simple words are: I hit you, you can hit me after you have endured, I endure...
full duplex
Allows data to be transmitted in both directions simultaneously.
For example, mobile phone calls, WebSocket is like this!
Simple: two people can fight each other at the same time
So much said is really to let you know that WebSocket s support two-way communication!
Advantages of two-way communication
Why support two-way communication?What's wrong with one-way communication? Or starting with HTTP, we know that the HTTP protocol is half duplex and the server can't actively push messages to the browser!This is his defect.If I want to implement a stock trading system, the stock price may change every second, but how do we inform our clients that the price has changed?
Let's see how it was done before!
polling
What is polling?Just keep asking!To be frank, the client sends requests to the server on a regular basis.
Short Polling
Section code, Talk is cheap,show me your code.
const express = require("express"); const app = express(); // The express ion static service middleware is used to return static files app.use(express.static(__dirname)); // The current price is 100 yuan let currentPrice = 100; // Get the latest price interface app.get("/getPrice", (req, res, next) => { res.send('¥'+currentPrice * Math.random()); }); app.listen(3000);
The client keeps sending requests to the server to get the latest price.
<div>Current transaction price: <span id="price"></span></div> <script> setInterval(() => { fetch('/getPrice'). then(res=>res.text()). then(data=>price.innerHTML = data) }, 1000); </script>
We soon saw the drawbacks of writing code like this!If the data doesn't change quickly, you'll send many meaningless requests.HTTP headers consume a lot of traffic and CPU utilization for every request sent!
long polling
Long polling is an improved version of short polling by sending the next request when the first one returns!
(function poll(){ fetch('/getPrice'). then(res=>res.text()). then(data=>{price.innerHTML = data;poll()}) })()
The problem is still obvious!If the server-side data changes rapidly, the number of requests will increase; if it changes very slowly, ajax may experience a timeout problem.
Iframe mode
We don't want to create a new request every time, so we can use Iframe for long connections
app.get("/getPrice", (req, res, next) => { setInterval(()=>{ // You can't use an end or the request will be interrupted. What we want to achieve is a long connection res.write(` <script> parent.document.getElementById('price').innerHTML = ${currentPrice * Math.random()} </script> `); },1000); });
<body> <div>Current transaction price: <span id="price"></span></div> <iframe src="/getPrice" frameborder="0"></iframe> </body>
You can now use Iframe for long-connection communication, but the state of the page has always been loaded!
EventSource Stream
The EventSource interface is used to receive events sent by the server.It connects to a server over HTTP to receive events in text/event-stream format without closing the connection.
<div>Current transaction price: <span id="price"></span></div> <script> const eventSource = new EventSource('/getPrice'); eventSource.onmessage = function(e){ // Get Received Data price.innerHTML = e.data; } </script>
app.get("/getPrice", (req, res, next) => { res.header('Content-Type','text/event-stream',); timer = setInterval(()=>{ res.write( // Sending message event\n\n indicates the end of current event-stream communication `event:message\nid:${id++}\ndata:${currentPrice*Math.random()}\n\n` ); },1000); res.on('close',()=>{ clearInterval(timer); }); });
Of course, this method is still one-way, mainly the server pushes data to the client.And compatibility is not beautiful~
WebSocket
Wait for you at last! The WebSocket for two-way communication stops you!
WebSocket s allow both clients and servers to maintain a persistent connection and start sending data at any time!It is based on the TCP protocol:
Let's talk about the benefits of WebSocket s first!
- http protocol does not support two-way communication - > I support two-way communication
- http protocol packet header is large - > my header is small!I need at least two bytes
- http does not support cross-domain - > I support cross-domain, haha!
ws module
ws: a Node.js WebSocket library, ok is the WebSocket library that can be used in a node!
Install ws module
yarn add ws
Server opens WebSocket service
const WebSocketServer = require('ws').Server; const ws = new WebSocketServer({port:8888}); ws.on('connection',(socket)=>{ // socket links my man console.log('Server:Someone is linking me!'); socket.on('message',(data)=>{ console.log(data); // Receive messages from clients socket.send('I'm a server'); // Send messages to clients }); });
Client links to the ws service on port 8888!
const socket = new WebSocket('ws://localhost:8888'); socket.onopen = function(){ // Send a message when the link is successful console.log('Client:Link succeeded'); socket.send('I am a client'); } socket.onmessage = function(e){ // Listen for information from clients console.log(e.data); }
Clients and servers can communicate happily with each other!
socket.io
Socket.io is a WebSocket library that includes both client-side js and server-side nodejs. Was it too early to be happy and forget about compatibility issues?Yes, socket.io is designed to help you solve the problem of automatically choosing the best way to implement real-time web applications based on your browser from WebSocket, AJAX Long Polling, Iframe Streaming, etc.
Install socket.io module
yarn add socket.io
Link through socket.io
const express = require("express"); const app = express(); app.use(express.static(__dirname)) const server = require('http').createServer(app); // app itself is a listening function // Sockets need http services const io = require('socket.io')(server); // Partition Path/ io.of('/').on('connection',function(socket){ console.log('Link succeeded') socket.on('message',function(msg){ console.log(msg); socket.send('I'm a server'); }); }); // Listen on port 3000 server.listen(3000);
// By default, socket.io.js scripts are injected into the browser <script src="/socket.io/socket.io.js"></script> <script> const socket = io.connect('/'); socket.on('connect',()=>{ console.log('Link succeeded'); socket.send('I am a client'); }); // Print the message when it is received socket.on('message',(data)=>{ console.log(data); }); </script>
Is it easy for us to have socket.io for two-way communication?
Does this help you?Please share with more people
Focus on "Front End Selection" plus star to improve front end skills
Focus on the Public Number for more advanced front-end skills
Add me WeChat: webyouxuan