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:
, dataType: "json"
, data: { since: CONFIG.last_message_time, id: CONFIG.id }
, 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.