This is the 12th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Http polling

Polling is when the browser sends an HTTP request to the server at a specific interval (e.g., every 1 second), and the server returns the latest data to the client’s browser. This traditional HTTP request pattern has obvious drawbacks – the browser needs to make continuous requests to the server, but the HTTP request header is very long, and the useful data contained in it may be only a small value, which consumes a lot of bandwidth.

Web Sockets

Polling and long polling are both http-based and have their own drawbacks: polling requires faster processing; Long polling requires the ability to handle concurrency; Both are examples of a “passive server” : the server does not actively push information, but rather responds when the client sends an Ajax request. And the ideal model is “in the server-side data changes, can actively push to the client “, this” active “server is a good solution to this kind of problem. Web Sockets are one such solution.

npm init -y && npm install -S ws
Copy the code

Node client or web browser client

Web Socket Node client

// client.js
let WebSocket = require('ws');
let socket = new WebSocket('the ws: / / 127.0.0.1:2000 /');
socket.on('open'.function(){
  socket.send('Hello, server, this is client.');
});
socket.on('message'.function(event){
  console.log(event);
})
Copy the code

Web Socket Web browser client

<! -- index.html -->

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
</head>

<body>

</body>
<script>
  // Web Socket client
  var socket = new WebSocket('ws: / / 127.0.0.1:2000');

  socket.addEventListener('open'.function (event) {
    socket.send('Hello Server! ');
  });

  // Listen for messages
  socket.addEventListener('message'.function (event) {
    console.log('Message from server ', event.data);
  });
</script>

</html>
Copy the code

Static server

// server.js
let fs = require('fs');
let http = require('http');
const PORT = 3000;

// Create a static server using HTTP
http.createServer(function (req, res) {
  fs.readFile(__dirname + req.url, function (err, data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    return res.end(data);
  });
}).listen(PORT);
console.log(` http://127.0.0.1:${PORT}/index.html`)
Copy the code

Web Socket server

// ws.server.js
let Server = require('ws').Server;
let wss = new Server({
  port:2000
});
wss.on('connection'.function(ws){
  ws.on('message'.function(buffer){
    ws.send('Hello, client, this is the server! ');
    console.log("Client information:",data.toString()); })});Copy the code