Push Technology
By establishing a long connection between the client and the server, the client can receive messages sent by the server from time to time.
(1) polling method based on ajax:
Using JQuery encapsulated $. ajax to build polling is shown below, and the polling is conducted every five seconds, regardless of whether the request is successful or not.
function push_ajax(callback) { $.ajax({ type: "GET", url: "", dataType: "", success: function(resp) { callback(resp); }, complete: function(resp) { setTimeout(function() { push_ajax(callback); }, 5000); } }); }
② Comet:
Http request is based on TCP connection. The process can be summarized as follows: the client establishes a TCP connection with the server, the server processes and generates Html text according to the message submitted by the client, closes Html into Http protocol message and returns it to the client, closes the connection.
It is not difficult to imagine that if the shutdown link is cancelled, the connection can be maintained, so that the server can send data to the client in real time through some operations, so as to reduce the overhead caused by the continuous establishment and release of the connection.
Based on Http long connection server push technology, there are three main implementations: long-polling, iframe and htmlfile streaming.
The difference between using ajax long polling to implement Comet and traditional ajax applications lies in:
The server will block the request until there is data transfer or a timeout.
The client JavaScript response handler will issue a request again and re-establish the connection after processing the information returned by the server.
When the client processes the received data and re-establishes the connection, the server may have new data arriving; the information will be saved by the server until the client re-establishes the connection, and the client will retrieve all the information from the current server at once.
By embedding a hidden iframe frame in the Html page, and then setting the src attribute of the hidden frame to a request for a long connection, the server can continuously input data to the client. Instead of returning the data directly displayed on the page, the server returns the call to the client Javascript function, passing the returned data as parameters of the function.
③ Server-Sent:
Simply put, Sever-Sent is Comet under Html5 specification, which has better uniformity.
Flash and socket:
Let's not dwell on it for the moment.
④ WebSocket:
The purpose of WebSocket is to solve the problem of two-way communication in network transmission (the client needs to transmit data to the server, and the server also needs to transmit information to the client in real time. Chat system is a typical two-way communication).
WebSocket is a persistent protocol that is partially implemented based on Http (default ports for ws and ws are 80 and 443).
socket.io(https://socket.io/ ) It is a relatively simple and practical WebSocket building service. Taking Express framework based on nodejs as an example, its bin/www file is modified as follows:
#!/usr/bin/env node /** * Module dependencies. */ var app = require("../app"); var debug = require("debug")("nv:server"); var server = require("http").createServer(app); var io = require("socket.io")(server); /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || "5000"); app.set("port", port); /** * Create HTTP server. */ // server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on("error", onError); server.on("listening", onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort (val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError (error) { if (error.syscall !== "listen") { throw error; } var bind = typeof port === "string" ? "Pipe " + port : "Port " + port; // handle specific listen errors with friendly messages switch (error.code) { case "EACCES": console.error(bind + " requires elevated privileges"); process.exit(1); break; case "EADDRINUSE": console.error(bind + " is already in use"); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening () { var addr = server.address(); var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port; debug("Listening on " + bind); } /** * Socket.io. */ io.on("connection", function (socket) { socket.on("disconnect", function () { // TODO }); socket.on("chat message", function (msg) { io.emit("chat message", msg); }); });
The front-end core code is as follows:
function initChart() { // Dom let chartDiv = document.getElementById("chart"); let contentDiv = chartDiv.querySelectorAll(".content")[0]; $(contentDiv).append(` <div class="whtsurname"> <h3>What's your name?</h3> <input type="text" id="nickname" maxlength="13"> </div> <div class="wrapper"> <ul id="messages"></ul> </div> <div class="form"> <input id="m" autocomplete="off" placeholder="Type here ..." /> </div> `); // Socket window.socket = io("http://mbs.jacqueline.engineer:5000"); // Unique color socket.color = colors[parseInt(Math.random() * colors.length)]; // Bind socket.on("chat message", function (msg) { $("#messages").append($(` <li><span class="nickname" style="color: ${msg.color};">${msg.name}</span>: ${msg.content}</li> `)); }); } $("#chart").on("keydown", "#m", function (e) { if (e.keyCode === 13) { let $input = $(this); socket.emit("chat message", {name: socket.nickname, content: $input.val(), color: socket.color}); $input.val(""); return false; } });
It can realize simple online multi-person chat function.