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;防止货物受潮、失火、…

[vue] vue和react有什么不同?使用场景分别是什么?

[vue] vue和react有什么不同&#xff1f;使用场景分别是什么&#xff1f; 1、vue是完整一套由官方维护的框架&#xff0c;核心库主要有由尤雨溪大神独自维护&#xff0c;而react是不要脸的书维护&#xff08;很多库由社区维护&#xff09;&#xff0c;曾经一段时间很多人质疑vu…

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)) 运行结果&…

[vue] 什么是双向绑定?原理是什么?

[vue] 什么是双向绑定&#xff1f;原理是什么&#xff1f; 双向数据绑定个人理解就是存在data→view,view→data两条数据流的模式。其实可以简单的理解为change和bind的结合。目前双向数据绑定都是基于Object.defineProperty()重新定义get和set方法实现的。修改触发set方法赋值…

私有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 "--------…

[vue] 什么是虚拟DOM?

[vue] 什么是虚拟DOM&#xff1f; 虚拟 dom 是相对于浏览器所渲染出来的真实 dom 的&#xff0c;在react&#xff0c;vue等技术出现之前&#xff0c;我们要改变页面展示的内容只能通过遍历查询 dom 树的方式找到需要修改的 dom 然后修改样式行为或者结构&#xff0c;来达到更新…

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;为什么…

[vue] vue组件之间的通信都有哪些?

[vue] vue组件之间的通信都有哪些&#xff1f; 父子Coms: 1/2/3 ..兄弟Coms: 4/5跨级Coms: 4/5/6/7props$emit/$on( $parents/$children ) / $refsVuexBus( provide/inject )( $attrs/$listeners )个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&…

linux中配置phpcms v9 中的sphinx

#MySQL数据源配置&#xff0c;详情请查看&#xff1a;http://www.coreseek.cn/products-install/mysql/2 #请先将var/test/documents.sql导入数据库&#xff0c;并配置好以下的MySQL用户密码数据库34 #源定义56 source news_news7 {8 type mysql9 …

Microsoft Visio绘图

2000年微软公司收购同名公司后&#xff0c;Visio成为微软公司的产品。Microsoft Visio是Windows 操作系统下运行的流程图软件&#xff0c;它现在是Microsoft Office软件的一个部分。Visio可以制作的图表范围十分广泛&#xff0c;有些人利用Visio的强大绘图功能绘制地图、企业标…

[vue] 请描述下vue的生命周期是什么?

[vue] 请描述下vue的生命周期是什么&#xff1f; 生命周期就是vue从开始创建到销毁的过程&#xff0c;分为四大步&#xff08;创建&#xff0c;挂载&#xff0c;更新&#xff0c;销毁&#xff09;&#xff0c;每一步又分为两小步&#xff0c;如beforeCreate&#xff0c;create…

HTTP返回码中301与302的区别

一&#xff0e;官方说法 301&#xff0c;302 都是HTTP状态的编码&#xff0c;都代表着某个URL发生了转移&#xff0c;不同之处在于&#xff1a; 301 redirect: 301 代表永久性转移(Permanently Moved)。 302 redirect: 302 代表暂时性转移(Temporarily Moved )。 这是很官方…

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

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

mysql的命令行安装,忘记密码,密码重置问题

1.下载&#xff0c;安装msi 2.在MYSQL安装目录下&#xff0c;新建data目录 3.进入MYSQL的安装目录下&#xff0c;新建一个默认配置文件my.ini [mysql] # 设置mysql客户端默认字符集 default-character-setutf8 [mysqld] #设置3306端口 port 3306 # 设置mysql的安装目录 base…

电话邦php面试题及答案

程序设计; 1.200个数位于数组$a中,均为[1,199]之间的整数,仅有一个数和其他的重复,请用程序找出这个重复的数,算法尽量快速. 答案: function Repeat($a){ $unique_arr array_unique($a); $repeat_arr array_diff_assoc($a,$unique); return $repeat_arr; } $repeat_a…

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

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