最近學習node,看了不少教程,都在讚賞nodejs的異步I/O,異步I/O的特色就是,每接收一個請求,使用異步調用處理請求,不用等待結果,能夠繼續運行其餘操做,也就是說能夠繼續接受請求。那它到底能接受?因而,我寫了個程序來測試,代碼以下:node
// server.js // 處理一個請求須要5秒,經過setTimeout設置5秒後響應 var http = require("http"); var n = 0; http.createServer(function (req, res) { n++; setTimeout(function() { console.log("Accept " + n + "request."); res.end("test"); }, 5000); }).listen(3000);
// client.js // 發送一個請求 exports.send = function () { var http = require('http'); var options = { host: 'localhost', port: '3000', path: '/', method: 'GET', }; var req = http.request(options, function(res){ exports.counter += 1; res.setEncoding('utf8'); res.on('data', function (c) { //console.log(c); }); res.on('end', function() { exports.seccess += 1; console.log("Response: " + exports.seccess); }); }); req.end(); }; exports.seccess = 0;
// attack.js // 在1秒內發出約50000個請求 var client = require('./client'); var d = 1000, t = Date.now(); while(Date.now() - t < d) { client.send(); } console.log('end.');
運行server.jsmarkdown
> node server.js
運行atack.js發起請求,(經測試每秒能發出約50000個請求):異步
> node atack.js
結果:socket
Accept 5request. Accept 5request. Accept 5request. Accept 5request. Accept 5request. Accept 10request. Accept 10request. Accept 10request. Accept 10request. Accept 10request. Accept 15request. Accept 15request. Accept 15request. Accept 15request. Accept 15request. // 省略後面N條
經過結果能夠知道server.js在5秒內只接受了5個請求,這是爲何呢?學習
Node.js 的 socket 模塊的一個限制致使的,好像是同一 IP 不能鏈接超過 5 個 socket。測試
試試 require('http').globalAgent.maxSockets = Infinity
ui