gpt4 book ai didi

node.js - 两个http请求能走到一起吗?如果可以,nodeJS 服务器如何处理它?

转载 作者:可可西里 更新时间:2023-11-01 02:44:49 27 4
gpt4 key购买 nike

昨天我做了一些关于 nodeJS 的演讲。有人问我以下问题:

As we know nodeJS is a single threaded server, several request iscoming to the server and it pushes all request to event loop. What iftwo request is coming to server at exact same time, how server willhandle this situation?

我猜到了一个想法并回复如下:

I guess No two http request can come to the server at exact sametime, all request come through a single socket so they will be in queue. Httprequest has following format:

httpPctFormt

timestamp of request is contained in it's header and they may be pushed to the event loop depending upon their timestamp in header.

但我不确定我给他的答案是对还是错。

最佳答案

I guess No two http request can come to the server at exact same time, all request come through pipe so they will be in queue.

这部分基本正确。传入连接进入事件队列,其中一个必须首先放入队列。

What if two request is coming two server at exact same time, how server will handle this situation?

由于服务器在单个进程中的单个套接字上监听传入的 TCP 连接,因此不可能同时有两个传入连接。一个将由底层操作系统稍早于另一个进行处理。这样想。传入连接是网络连接上的一组数据包。其中一个传入连接将在另一个连接之前收到其数据包。

即使您有多个网卡和多个网络链接,因此两个传入连接实际上可以在同一时刻到达服务器,node.js 队列将通过互斥锁和其中一个传入连接来保护并发连接将先于其他连接获取互斥锁,并先于其他连接进入事件队列。

首先被操作系统处理的事件会先于另一个事件被放入 node.js 事件队列。当 node.js 可用于处理事件队列中的下一个项目时,事件队列中最先进入的请求将首先开始处理。

因为 node.js JS 执行是单线程的,请求的代码处理将运行其同步代码直至完成。如果它有一个异步操作,那么它将启动那个异步操作并返回。然后将允许处理事件队列中的下一个项目,第二个请求的代码将开始运行。它将同步运行到完成。与第一个请求一样,如果它有一个异步操作,那么它将启动该异步操作并返回。

此时,在两个请求都开始了它们的异步操作然后返回之后,就到了事件队列了。当其中一个异步操作完成时,它会将另一个事件发布到事件队列中,当 node.js 的单线程空闲时,它将再次处理事件队列中的下一个项目。如果两个请求都有很多异步操作,它们的进度可能会交错,并且在它们触发异步操作的同时都可能处于“飞行中”,然后返回直到异步操作完成,当 node.js 运行时它们的处理再次开始可以自由处理下一个事件。

timestamp of request is contained in it's header and they may be pushed to the event loop depending upon their timestamp in header.

这部分不太对。相同类型的传入事件在到达时添加到队列中。第一个到达的首先进入队列 - 没有任何检查时间戳的步骤。

关于node.js - 两个http请求能走到一起吗?如果可以,nodeJS 服务器如何处理它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40571109/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com