和小伙伴聊天的時候聊到chrome瀏覽器下轴或,一個頁面最大并發(fā)請求限制只有6個的問題,突然靈光一閃仰禀。一個頁面限制最大6個并發(fā)照雁,那兩個頁面同時請求是不是就是12個?如果是的話答恶,那么能不能通過多開標(biāo)簽頁饺蚊,然后通過頁面間的消息通訊,達(dá)到突破6個并發(fā)請求的限制呢悬嗓?
先說結(jié)論:不能污呼,是我想多了!同一個域名的多個標(biāo)簽頁包竹,共用6個最大并發(fā)請求限制燕酷。
測試流程如下:
服務(wù)端建立實驗接口,人為增加900毫秒延遲映企。前端打開index.html 和index2.html,兩個頁面同時發(fā)起100個請求悟狱。如果服務(wù)端接口處理方法中輸出的信息能同時輸出12個,那證明該方法可行堰氓。反之不能挤渐。
話不多說,上代碼
服務(wù)端用的nodejs + Koa
const Koa = require('koa');
const Router = require('@koa/router');
const serve = require('koa-static');
const app = new Koa();
const http = require('http');
const router = new Router();
app.use(serve(__dirname + '/static'));
let n = 0;
router.get('/a', async (ctx, next) => {
await wait(900);
ctx.body = ++n;
console.log(n);
});
app
.use(router.routes())
.use(router.allowedMethods());
const httpServer = http.createServer(app.callback());
httpServer.listen(3000);
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
測試頁面代碼:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<button id="open">open</button>
<script>
function get(popup){
fetch('./a')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson)
popup.postMessage(myJson, "*");
});
}
window.onload = function(){
let button = document.querySelector('#open');
button.addEventListener('click',o);
}
function o(){
var popup = window.open('./index2.html');
setTimeout(()=>{
let n = 100;
while(n--){
get(popup);
}
},2000)
}
</script>
</body>
</html>
index2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Minimal working example</title>
</head>
<body>
<ul id="events"></ul>
<script>
function get(){
fetch('./a')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
function receiveMessage(event)
{
console.log('receive ',event.data);
}
window.onload = function(){
window.addEventListener("message", receiveMessage, false);
let n = 100;
while(n--){
get();
}
}
</script>
</body>
</html>
實驗結(jié)果:
服務(wù)端接收到的請求還是6個一組双絮。失敗了浴麻。