


How does the node.js chat program implement Ajax long-polling long link refresh mode_javascript skills
Without further ado, let’s start today’s topic. Looking at this program, I feel that the most valuable thing about it is that it shows how to use nodejs to implement the refresh technology of long link mode.
(This program will not be introduced in detail, but the focus will be on this function)
Client.js
The code is as follows:
, error: function () {
addMessage("", "long poll error. trying again...", new Date(), "error");
transmission_errors = 1;
//don 't flood the servers on error, wait 10 seconds before retrying
setTimeout(longPoll, 10*1000);
}
, success: function (data) {
transmission_errors = 0;
//if everything went well, begin another request immediately
//the server will take a long time to respond
//how long? well, it will wait until there is another message
//and then it will return it to us and close the connection.
//since the connection is closed when we get data, we longPoll again
longPoll(data);
}
});
}
This is a piece of code in client.js. When you look at this code, you should immediately think of two words - "recursion". In the longPoll method, call the longPoll method again, a typical recursive call.
Based on the semantics of this code, it can be seen that when loading for the first time, the longPoll method will be called to asynchronously obtain the value from "/resv". If successful, the success method will be executed and the longPoll method will be called again immediately. If it fails, execute the error function and call the longPoll method again every 10 seconds. Of course, there is a certain limit on the number of times the error method can be executed, which is controlled by the variable transmission_errorsx.
You may have a question, will the server be burdened with recursively looping to obtain data? Will this cycle continue when there is no data to obtain? Of course, the answer is no! Moreover, nodejs uses its own characteristics to solve this problem very well. Then look down:
Server.js
Now look at how the server responds to the above client call, the core code:
Copy code
The code is as follows:
Don’t worry about what fu.get() means, it has nothing to do with this tutorial. In short, just know that it can respond to the client's call. The above code, in addition to some operations on the session, just calls the query method of the channel. Pay attention to the parameters passed:
since, which records a time;
Anonymous method, which accepts a messages parameter and two actions: 1. Update the session time, 2. Return a json, that is, return messages to the client.
Some people may have questions: Isn’t it possible to directly return messages here? Why do we need to define a method in a channel to operate? Answer: If so, it becomes an infinite loop. The server and client are interacting with data all the time, even if there is no information to return.
Let’s read on!
See how channel is defined:
Copy the code
The code is as follows:
var MESSAGE_BACKLOG = 200,
SESSION_TIMEOUT = 60 * 1000;
var channel = new function () {
var messages = [],
callbacks = [];
this.appendMessage = function (nick, type, text) {
var m = { nick: nick
, type: type // "msg", "join", "part"
, text: text
, timestamp: (new Date()).getTime()
};
switch (type) {
case "msg":
sys.puts("<" nick "> " text);
break;
case "join":
sys.puts(nick " join");
break;
case "part":
sys .puts(nick " part");
break;
}
messages.push( m );
while (callbacks.length > 0) {
//shift() method Used to delete the first element of the array from it and return the value of the first element
callbacks.shift().callback([m]);
}
while (messages.length > ; MESSAGE_BACKLOG)
messages.shift();
};
this.query = function (since, callback) {
var matching = [];
for (var i = 0; i < messages.length; i ) {
var message = messages[i];
if (message.timestamp > since)
matching.push(message)
}
if (matching.length != 0) {
callback(matching);
} else {
callbacks.push({ timestamp: new Date(), callback: callback });
}
};
// clear old callbacks
// they can hang around for at most 30 seconds.
setInterval(function () {
var now = new Date();
while (callbacks.length > 0 && now - callbacks[0].timestamp > 30*1000) {
callbacks.shift().callback([]);
}
}, 3000);
};
Two variables, two methods, and a setInterval function that are executed every 3 seconds are defined in the channel.
First look at the query method,
The query method receives two parameters:
since: records a time
callback: the anonymous function passed in when calling the channel.query method mentioned above (in JS, The function can be passed as a parameter and can be called directly after receiving it. .)
The current chat record queue is stored in messages, and the query method will find the chat records that meet the conditions and put them in matching. in queue. If matching.length>0, the function received by the callback is called, that is, the matching is returned to the client in json format. but. . . Next is the key point! ! !
if (matching.length != 0) {
callback(matching);
} else {
callbacks.push({ timestamp: new Date(), callback: callback });
}
if matching.length< ;=0, the program will store the callback and the current time in json format into a callbacks queue. right! It will not be executed because there is no chat message that meets the conditions and does not need to be displayed on the client, so this function is saved first and not executed.
Then you can’t keep it like this forever. What if someone sends a chat message every second?
Then look at the appendMessage (add chat message) method:
In this method, the first part is easy to understand. It is nothing more than receiving the incoming parameters, combining them into an m set, and then using sys.puts to display it on the terminal. Then insert m into the messages chat message queue. Next is the key point:
while (callbacks.length > ; 0) {
//shift() method is used to delete the first element of the array and return the value of the first element
callbacks.shift().callback([m]);
}
Now we need to determine whether the callbacks are stored. If so, execute one and delete one until the execution is completed. Because before there was no chat message to return, someone made a request, and then the system did not execute these requests and put them in the callbacks list.
Now that someone has sent a chat message, when executing the add method, all unexecuted requests must be executed again.
Popular understanding can be: You sent me a request, but I don’t have any new messages to reply to you yet. Once someone sends a new message, I will reply to you immediately.
I don’t know if you understand it. . .
This step is finished. The last step is to clear expired callbacks every 3 seconds. It is a setInterval function. This is not difficult to understand.
Summary
Nodejs uses its own event-driven language features to implement the long link refresh function, which opens our eyes. I feel I have benefited a lot. I would like to take the time to write a tutorial to share with you, and also to deepen my own understanding.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Currently, Microsoft offers three different AI assistants to enterprise customers: Microsoft365Copilot, BingChatEnterprise, and Copilot in Windows. We would like to explain the differences between these three options. CopilotinWindows: Copilot in Windows is a powerful tool that helps you complete tasks faster and easier. You can seamlessly access Copilot from the taskbar or by pressing Win+C, and it will provide help next to any application you use. Copilot in Windows features new icons, new user experience and BingChat. it will be 2

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package
