我正在研究一個node.js應用程序,該應用程序必須向大約10,000個用戶提供實時服務器推送。我的目標是最小化第一個接收器和最後一個接收器之間的時間差。現在,我正在我的機器上進行本地開發。使用node.js一次處理10,000個併發請求
我使用一個循環來生成請求,然後阻止服務器響應,直到它達到10,0000個請求。我希望服務器能夠一次廣播所有請求並測量差異。
request.js
var http = require('http')
, a = http.getAgent('127.0.0.1', 9202);
var util = require('util');
var connections = [];
var NUM_CONCURR = 1000;
// Max and Min
Array.prototype.max = function(){
var max = this[0];
var len = this.length;
for(var i=0; i<len;i++)
if(this[i]>max)
max = this[i];
return max;
};
Array.prototype.min = function(){
var min = this[0];
var len = this.length;
for(var i=0; i<len; i++)
if(this[i]<min)
min = this[i];
return min;
};
// Number of socket tested
a.maxSockets = Infinity;
for(var i =0; i<NUM_CONCURR; i++){
http.get({
agent: a,
path: '/',
port: 9202,
host: '127.0.0.1'
},function(res){
connections.push(microtime(true));
});
util.log("Connected Clients: "+i);
}
util.log("Server running at port 9202");
setInterval(function(){
util.log("Total Diff Time = "+(connections.max()-connections.min()));
connections =[];
}, 1000*10);
// Time function
function microtime(get_as_float) {
var now = new Date().getTime()/1000;
var s = parseInt(now);
return (get_as_float) ? now : (Math.round((now - s) * 1000)/1000) + ' ' + s;
}
server.js
var http = require('http'),
HOST = 'localhost',
PORT = '9202';
var connections = [], i;
var server = http.createServer(function(req, res){
connections[connections.length] = {req:req, res:res};
console.log('established connections: '+ ++i);
});
// Send msg to stored connections
function message(){
var i = connections.length,
connection;
while(i--){
connection = connections[i];
connection.res.writeHead(200);
connection.res.write('weeeee');
}
};
//Broadcast after 40 sec
setTimeout(function(){
message();
}, 1000*40);
server.listen(PORT);
console.log('listening on 9202');
這出於某種原因,我沒有工作。有更好的方法嗎?誰能分享他的想法?你有什麼時差?謝謝。
當你說它不適合你時,意味着什麼?你期望什麼產出,你收到了什麼? – BCG 2011-06-15 23:02:28