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

Can two http request come together? If it can, how nodeJS server handles it?

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

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

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

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

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

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

多个并发 HTTP 请求不是问题。 Node.js 是异步的,将在事件循环中处理多个请求,而不必等待每个请求完成。

供参考,例如:

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 队列将通过互斥锁等方式保护并发其中一个传入连接将先于另一个连接获取互斥锁,并先于另一个连接进入事件队列。

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

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

此时,在两个请求都开始了它们的异步操作然后 returned 之后,它就进入了事件队列。当其中一个异步操作完成时,它将 post 另一个事件添加到事件队列中,当 node.js 的单个线程空闲时,它将再次处理事件队列中的下一个项目。如果两个请求都有很多异步操作,它们的进度可能会交错,并且在触发异步操作时两者都可能 "in-flight" 然后 return 直到异步操作完成,当它们的处理再次开始时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.

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