我有以下服务器代码。使用Node.js和ajax进行长查询
var http = require('http');
var mysql = require('mysql');
var querystring = require('request');
var util = require('util');
var url = require('url');
var singer_name;
var currentmodif, lastmodif;
var requests=[];
var response;
var connection = mysql.createConnection({
host : 'localhost',
user : 'someone',
password : 'xxxxxxx',
database : 'rest', //mysql database to work with (optional)
});
connection.connect(); //connect to mysql
connection.query('SELECT * FROM musics WHERE id=1', function(err, rows, fields) {
if (err) throw err;
singer_name=rows[0].singer_name;
currentmodif=rows[0].time_added;
});
http.createServer(function (req, res) {
console.log('request received');
requests.push({
response: res,
timestamp: new Date().getTime()
});
if(req.method=='GET'){
var url_parts = url.parse(req.url,true);
lastmodif = url_parts.query.timestamp;
}
//check_update(req, res);
}).listen(9000);
setInterval(function() {
var expiration = new Date().getTime() - 30000;
for (var i = requests.length - 1; i >= 0; i--) {
//console.log("Request timestamp: "+requests[i].timestamp+" Expiration : "+expiration);
response = requests[i].response;
if (requests[i].timestamp < expiration) {
console.log("The condition is met");
response.writeHead(200, {
'Content-Type' : 'text/plain',
'Access-Control-Allow-Origin' : '*'
});
// return response
response.write('_testcb(\'ok\')', 'utf8');
response.end();
//break;
}
}
connection.query('SELECT * FROM musics WHERE id=1', function(err, rows, fields) {
if (err) throw err;
currentmodif=rows[0].time_added;
//console.log("currentmodif: "+currentmodif+" lastmodif: "+lastmodif);
if (currentmodif > lastmodif){
singer_name=rows[0].singer_name;
var _arrays = {'singer_name': singer_name, 'time': currentmodif}
var data = "_testcb"+"("+JSON.stringify(_arrays)+")";
response.writeHead(200, {
'Content-Type' : 'text/plain',
'Access-Control-Allow-Origin' : '*'
});
if (response.end(data))
console.log("Response successfully sent");
//return false;
}
});
}, 2000);
和客户端代码:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<title>Node.js Ajax test</title>
</head>
<body>
</body>
<script>
var timestamp = "1380020402";
function callNode() {
var time = "1380020402";
$.ajax({
url: 'http://xx.xxx.xx.xxx:9000/',
dataType: "jsonp",
data: {"timestamp":timestamp},
type: 'POST',
jsonpCallback: "_testcb",
cache: false,
timeout: 35000,
success: function(response, code, xhr) {
if ('ok' == response) {
callNode();
return false;
}
console.log(response);
timestamp = response.time;
// make new call
callNode();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus + " " + errorThrown);
}
});
}
$(function() {
callNode();
});
</script>
</html>
我试图做一个长轮询。因此,在数据库中的数据更新之前,应该暂停对ajax请求的响应,但上述代码不起作用。我正在从不同的域名发出ajax请求,因此使用jsonp。
确切的问题是,当前数据在数据库中发生变化时,响应没有得到发送。它时不时地工作,但它并不总是可靠的。
另一个问题是超时代码块不工作。如果请求的时间是30秒,那么应该发送一个空的响应以避免来自ajax的超时。
如果有人可以帮助,那么我将不胜感激。
干杯。
嗨。一直给函数的递归调用会导致堆栈溢出? –
我不认为会。我的服务器现在持续运行了一个多月,并没有造成任何溢出。也许node.js有一个机制来解决这个问题? – Sahil
它不会导致堆栈溢出。这实际上并不是递归,因为'callNode'是由$ .ajax请求的'success'回调调用的,而不是'callNode'自己调用的。一旦'callNode'发出请求,它就会退出。 –