Handling multiple parallel HTTP requests in Node.js

后端 未结 4 585
死守一世寂寞
死守一世寂寞 2021-01-07 19:12

I know that Node is non-blocking, but I just realized that the default behaviour of http.listen(8000) means that all HTTP requests are handled one-at-a-time. I

4条回答
  •  一生所求
    2021-01-07 19:23

    You are misunderstanding how node works. The above code can accept TCP connections from hundreds or thousands of clients, read the HTTP requests, and then wait the 4000 ms timeout you have baked in there, and then send the responses. Each client will get a response in about 4000 + a small number of milliseconds. During that setTimeout (and during any I/O operation) node can continue processing. This includes accepting additional TCP connections. I tested your code and the browsers each get a response in 4s. The second one does NOT take 8s, if that is how you think it works.

    I ran curl -s localhost:8080 in 4 tabs as quickly as I can via the keyboard and the seconds in the timestamps are:

    1. 54 to 58
    2. 54 to 58
    3. 55 to 59
    4. 56 to 00

    There's no issue here, although I can understand how you might think there is one. Node would be totally broken if it worked as your post suggested.

    Here's another way to verify:

    for i in 1 2 3 4 5 6 7 8 9 10; do curl -s localhost:8080 &;done                                                                                                                                                                       
    

提交回复
热议问题