我想評估客戶端和服務器之間的往返時間。在這裏用戶可以選擇消息(正文)的請求/響應大小應該有多大。在客戶端,我使用Ajax-Post方法以100毫秒的間隔向http-server發送100條消息。 Unfortunatley我在node.js中遇到了問題,即httpServer.js無法處理大於8 kb的客戶端請求大小。在這種情況下,httpServer.js中的變量responseSizeServer將獲取值「undefined」,並且控制檯會引發錯誤:「數組長度無效」。問題是爲什麼在這種情況下,變量responseSizeServer的值是undefined?我猜想http-Server.js處理.end方法比來自客戶端的傳入請求更快。你認爲什麼?如何解決?感謝提前:)請求大於8 kb
下面是代碼:
客戶端:
var i = 0;
var iterations = 100;
function connectSpeed(){
run = window.setInterval("startSpeed()", 100);
}
function startSpeed()
{
//Variablen
var requestSizeClient = 8 *1024; // 8 kb request Size client
var responseSizeServer = 16 * 1024; // 16 kb response size server
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://localhost:8000", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var receiveTimeCl = new Date().getTime().toString();
//evaluate response from httpServer.js
var message = xmlhttp.responseText;
}
}
//send data to the server
xmlhttp.send(new Date().getTime().toString() + '#' + new Array((eval(requestSizeClient+1))-(new Date().getTime().toString().length+3)).join('X') + '#' + responseSizeServer);
i++;
if(i==iterations) {
window.clearInterval(run);
i=0;
}
}// end start-speed
服務器:在Node.js的(httpServer.js)
var http = require('http');
http.createServer(function (req, res) {
var receiveTimeServer;
var clientMsg;
var sendTimeClient;
var responseSizeServer;
var message;
req.on('data', function (chunk) {
receiveTimeServer = new Date().getTime().toString();
message = chunk.toString('utf8');
clientMsg = message.split('#');
responseSizeServer = parseInt(clientMsg[2]);
sendTimeClient = clientMsg[0];
res.writeHead(200, {'Content-Type': 'text/plain','Access-Control-Allow-Origin' : '*'});
res.end(receiveTimeServer + '#' + new Date().getTime().toString() + '#' + sendTimeClient + '#' + new Array(responseSizeServer).join('X'));
});
}).listen(8000);
console.log('Ajax_Server running');
非常感謝你,這是對的! – user3030559