Concurrent HTTP connections in Node.js

 

 

原文: https://fullstack-developer.academy/concurrent-http-connections-in-node-js/

------------------------------------------------------------------------------------------

Browsers, as well as Node.js, have limitations on concurrent HTTP connections. It is essential to understand these limitations because we can run into undesired situations whereby an application would function incorrectly. In this article, we will review everything that you, as a developer, need to be familiar with regarding concurrent HTTP connections.

Browser

Browsers adhere to protocols - and the HTTP 1.1 protocol states that a single client (a user client) should not maintain more than two concurrent connections. Now, some older browsers do enforce this, however, generally speaking, newer browsers - often referred to as "modern" browsers - allow a more generous limit. Here's a more precise list:

  • IE 7: 2 connections
  • IE 8 & 9: 6 connections
  • IE 10: 8 connections
  • IE 11: 13 connections
  • Firefox, Chrome (Mobile and Desktop), Safari (Mobile and Desktop), Opera: 6 connections

For the rest of this article remember the number 6 - this will play a crucial part when we go through our example.

Node.js

If you have worked with, learned or just read about Node.js before, you know that it is a single-threaded, non-blocking framework. This means that it allows a significant number of concurrent connections - all of this is made available by the JavaScript event loop.

The actual limit of connections in Node.js is determined by the available resources on the machine running the code and by the operating system settings as well.

Back in the early days of Node.js (think v0.10 and earlier), there was an imposed limit of 5 simultaneous connections to/from a single host. What does this mean? Under the hood when you are using the Node.js built-in HTTP module or any other module that uses the HTTP module like Express.js or Restify, you are in fact using a connection pool and HTTP keep-alive. This is great for performance improvement - think about the cycle like the following: an HTTP request is processed, this opens a TCP connection, for a new request an existing TCP connection can be used. (Without the keep-alive the process would be less performant by having to create a TCP connection, serve a response close the TCP connection and start this again for the next request)

In version higher than 0.10 the maxSockets value has been changed to Infinity.

The keep-alive is sent by the browser and we can easily see this if we log the request object in Node.js in the appropriate location. It should yield something similar to this (example taken from a Restify server):

headers:{ host: 'localhost:3000','content-type': 'text/plain;charset=UTF-8',origin: 'http://127.0.0.1:8080','accept-encoding': 'gzip, deflate',connection: 'keep-alive',

Example

Let's take a look at a very straightforward example. Let's assume that we have some sort of a frontend where we are sending data to a backend (this is usually how modern applications work, a frontend framework making requests to a Backend API). For the our example, the data that we are sending is less important - it's equally applicable to a bulk file upload or anything else.

Trivia: I have in fact came across this issue while working on an application that did a bulk upload of images and sent it to a backend API for further processing.

Let's create a simple Restify API server:

const restify = require('restify'); const corsMiddleware = require('restify-cors-middleware'); const port = 3000; const server = restify.createServer(); const bunyan = require('bunyan'); const cors = corsMiddleware({ origins: ['*'], }); server.use(restify.plugins.bodyParser()); server.pre(cors.preflight); server.use(cors.actual); server.post('/api', (req, res) => { const payload = req.body; console.log(`Processing: ${payload}`); }); server.listen(port, () => console.info(`Server is up on ${port}.`)); 

This is very straightforward. Astute readers would already have noticed a somewhat crucial mistake in the code above but don't worry; it is made deliberately. So this API receives data sent via an HTTP POST request and displays a log message stating that it is processing whatever was sent as part of the request. (Again, the processing could be whatever we wanted, but for this discussion, it's just a simple console statement.)

Let's also create a simple frontend. Let's create a very simple index.htmland add the following content in between <script> tags:

const array = Array.from(Array(10).keys()); array.forEach(arrayItem => { fetch('http://localhost:3000/api', { method: 'POST', mode: 'cors', body: JSON.stringify(`hello${arrayItem}`) }) .then(response => console.log(response.json())) .catch(error => console.error(`Fetch Error: `, error)); }); 

Here, the Fetch API is used to iterate through 9 items (mimicking an upload of 9 files for example) and sending 9 HTTP POST requests to the Restify API discussed earlier.

Start up the API, also load the index.html via an HTTP server and let's see the results.

Here are two easy ways of firing up an HTTP server in an easy way: either use python -m SimpleHTTPServer 8000 (v2) or python -m http.server 8080 (v3). Or do a global npm install of http-server and then just do http-server from the folder where you have the index.html file.

It's fascinating what we see. Even though we have made 9 HTTP POSTrequests only six have arrived to the Restify API since we see 6 log statements.

However, if you wait about 2 minutes, additional log statements will appear.

So what is going on here?

Remember what we said before - the browser (in this case Safari) is capable of making six requests to the same host (in this case the connection is between our browser and the API running on port 3000 on localhost).

The connection is kept alive because we are not returning anything from the Node.js API. This was the mistake that I have deliberately made to make a point. So the browser sends six requests, and Node.js receives these but it never sends any information back rendering the remaining requests to be blocked.

So why are the other log statements visible later? The answer is simple: there's also a timeout, which is by default 2 minutes. After 2 minutes the request is cleared, so new requests are processed.

Let's update our code with these values:

server.server.maxConnections = 20; function getConnections() { server.server.getConnections((error, count) => console.log(count)); } // add getConnections() in the API call: server.post('/api', (req, res) => { // ... getConnections(); }); 

The server.server.maxConnections = 20; is there just to make a point that no matter how big this number is it's not going to change the outcome because we are still not returning anything (remember it is set to be Inifity anyway):

However, add the following setting to change the behaviour:

server.server.setTimeout(500); 

The result is going to be a lot different. Since we are overwriting the timeout of the server, we only wait 500 ms and get rid of a pending request, allowing new requests to come in.

Please note that this is not a real solution to this problem, it is just for demonstration purposes.

Solving the problem

The right way to solve this problem is of course to return a response from the API:

server.post('/api', (req, res) => { const payload = req.body; console.log(`Processing: ${payload}`); return res.json(`Done processing: ${payload}`); }); 

Now all data is going to be processed just fine:

All uploads are now processed just fine.

Remember, res.json() under the hood uses res.send() which in turn also uses res.end() to send a response and to end it. This is true for both Restify and Express.js as well.

Conclusion

What is the moral of the story? Always close HTTP connections - no matter how, but close them - if you're making API calls consult the API documentation as well to close any active HTTP connection.

转载于:https://www.cnblogs.com/oxspirt/p/10367881.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/412294.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

形状相似的物品_空运一般货物及危险品和特殊物品对包装的要求和规定!

一.空运包装的基本作用1.包装的基本作用有三种&#xff1a;保护、保存和介绍。包装应在贮存期间和从制造厂运至消费中心期间&#xff0c;起到保护和保存内部货物的作用。保护货物不仅包括防止丢失、损坏和被盗&#xff0c;还包括根据货物的性质&#xff0c;防止货物受潮、失火、…

coreldraw x4怎么会蓝屏_CorelDRAW广告条幅批量制作插件

由VBA探秘站长个人开发的一款条幅插件&#xff0c;用于广告行业快速制作条幅的好帮手。 所有用户可以在这个开源的版本基础上二次开发完善。界面截图软件架构基于VBA语言开发&#xff0c;插件形式为GMS。安装教程如果是非开发者用户&#xff0c;想直接使用插件&#xff0c;请直…

Python中数字之间的进制转换

https://www.cnblogs.com/Kingfan1993/p/9795541.html 在python中可以通过内置方法进行相应的进制转换&#xff0c;但需记得转化成非十进制时&#xff0c;都会将数字转化成字符串 转化成二进制 a 10 #声明数字&#xff0c;默认十进制 b bin(a) print(b , type(b)) 运行结果&…

私有5g网络_Verizon与诺基亚合作部署私有5G网络

点击上方“IEEE电气电子工程师”即可订阅公众号。网罗全球科技前沿动态&#xff0c;为科研创业打开脑洞。SOPA Images via Getty ImagesVerizon宣布&#xff0c;Verizon将与诺基亚合作&#xff0c;创建私人5G设备&#xff0c;在大型“制造、分销和物流设施”中取代WiFi。这个想…

进程重启脚本

shell脚本杀进程重启 #!/bin/bash IDps -ef | grep "abc" | grep -v "$0" | grep -v "grep" | awk {print $2} echo $ID echo "---------------" for id in $ID do kill -9 $id echo "killed $id" done echo "--------…

layui多级联动下拉框的实现_简单三级联动的实现

当我们做一些例如注册页面的时候&#xff0c;可能会遇到要选择地址的操作&#xff0c;这时会出现三个选择框&#xff0c;当你选择省级单位的时候会自动在选择筐中&#xff0c;弹出她所属的市级单位的列表&#xff0c;当选择市级单位时又会弹出县级单位&#xff0c;我们要实现的…

django初探

首先在确保python已经安装之后(3.7), 安装django. 刚开始学习 只做了简单的测试 就是控制器与视图,路由的链接 首先 python manage.py startapp demo 使用此命令创建项目中的各个模块目录在各个目录中创建对应的子路由文件 然后将子路由文件引入到主路由文件中 也就是根目录的…

加载文件流_未关闭的文件流会引起内存泄露么?

专注于Java领域优质技术&#xff0c;欢迎关注来自&#xff1a;技术小黑屋最近接触了一些面试者&#xff0c;在面试过程中有涉及到内存泄露的问题&#xff0c;其中有不少人回答说&#xff0c;如果文件打开后&#xff0c;没有关闭会导致内存泄露。当被继续追问&#xff0c;为什么…

10截图时屏幕变大_手机上网课、开视频会议,如何让屏幕变大一点?

点击图片进入商城▲车载闪充49.9秒杀&#xff01;Reno2 Z直降200元&#xff01;真无线耳机团购可省130元&#xff01;这个特殊时期很多伙伴和小O一样在家远程云办公、线上会议学生朋友们也是在家参加网上课程虽然现在的手机屏幕越来越大但总盯着手机还是难免眼酸但是掌握这个手…

分层和分段用什么符号_小编带你学直播——后牙树脂分层堆塑

后牙龋损过大&#xff0c;患者又不想做冠修复&#xff0c;树脂修补真的能挽救被龋坏侵蚀的牙体吗&#xff1f;补牙看起来简单&#xff0c;但是补好却难&#xff0c;同事用分层堆塑补的后牙窝沟分明&#xff0c;有点想学...本周小编为你推荐吕春阳老师——《后牙树脂分层堆塑》专…

CSAPP:第十一章 网络编程

CSAPP&#xff1a;第十一章 网络编程 11.1 客户端服务器模型11.2 全球IP因特网11.3 套接字接口 11.1 客户端服务器模型 每个网络应用都是基于客户端-服务器模型。采用这个模型&#xff0c;一个应用是由一个服务器进程和一个或者多个客户端进程组成。  客户端-服务器模型的基本…

动态表格数据序号从1开始_EXCEL对面的表姐看过来,你真的会给表格添加序号吗?...

原创作者&#xff1a; EH看见星光 转自&#xff1a;Excel星球哈罗&#xff0c;大家好&#xff0c;我是星光&#xff0c;今天给大家总结分享的表格技巧是……序号。什么是序号&#xff1f;序号就是一二三四五上山打老虎……一二三四一二三四像首歌……一二三四二二三四脖子扭扭屁…

设置公共请求参数_基于分布式锁的防止重复请求解决方案(值得收藏)

关于重复请求&#xff0c;指的是我们服务端接收到很短的时间内的多个相同内容的重复请求。而这样的重复请求如果是幂等的(每次请求的结果都相同&#xff0c;如查询请求)&#xff0c;那其实对于我们没有什么影响&#xff0c;但如果是非幂等的(每次请求都会对关键数据造成影响&am…

【niop2016】

D1T1 玩具谜题 my总结&#xff1a; 【luogu1563】【niop2016】玩具谜题 题面 模拟&#xff01;&#xff01;&#xff01; D1T2 天天爱跑步 my总结&#xff1a; 暂无 题面 我太弱了还搞不出来 暴力也不想写 D1T3 换教室 my总结&#xff1a;【niop2016】【luogu1600】…

Linux 随机数

一、rand函数 rand函数的简单使用&#xff0c;rand()返回一个[0, RAND_MAX]中的随机数  #include <stdlib.h> #include <stdio.h> #include <time.h>int main() {printf("%d\n", RAND_MAX);//srand(time(NULL));for(int i 0; i < 5; i){print…

linux 2行数据为一条记录 该如何操作这一条记录_Linux 日志文件系统原来是这样工作的...

文件系统要解决的一个关键问题是怎样防止掉电或系统崩溃造成数据损坏&#xff0c;在此类意外事件中&#xff0c;导致文件系统损坏的根本原因在于写文件不是原子操作&#xff0c;因为写文件涉及的不仅仅是用户数据&#xff0c;还涉及元数据(metadata)包括 Superblock、inode bit…

JMeter - 如何创建可重用和模块化测试脚本

概述&#xff1a; 我的应用程序几乎没有业务关键流程&#xff0c;我们可以从中提出不同的业务工作流程。当我试图在JMeter中提出性能测试脚本时&#xff0c;我需要找到一些方法来创建可重用/模块化的测试脚本。这样我就可以创建不同的工作流程。 对于Ex&#xff1a; 让我们考虑…

请求支付宝渠道报错:40006,Insufficient Permissions,ISV权限不足

错误描述&#xff1a; 申请的是支付宝2.0产品&#xff08;如何区分支付宝产品是1.0还是2.0&#xff09;&#xff0c;请求支付宝渠道时&#xff0c;报错&#xff1a; {"code":"40006","msg":"Insufficient Permissions","sub_code…

idea中lombok的使用

1.安装插件 在File-Setting-Plugins-Browse Repostitories中搜索Lombok Plugin插件安装 安装完成先别急着重启&#xff0c;继续设置&#xff0c;在File-Setting-Build, Execution, Deployment-Compiler-Annotation Processors中点击Enable annotation processors 确定后重启ide…

是隐极电机_资料 | 发电机定子绕组端部动态特性试验详解

一、试验目的大型汽轮发电机运行过程中&#xff0c;定子端部受二倍工频(100Hz)的电磁激振力。如果定子端部的模态接近100Hz&#xff0c;将发生谐振&#xff0c;从而可能因振幅过大而发生结构松动、磨损、绝缘损坏等现象&#xff0c;甚至断裂等故障&#xff0c;严重威胁机组的安…