gpt4 book ai didi

javascript - 是否可以暂停/挂起(不要在套接字上接受(2))Node.js 服务器?

转载 作者:搜寻专家 更新时间:2023-10-31 23:59:22 25 4
gpt4 key购买 nike

目标:拥有一台同时只有一个连接处于事件状态的 Node.js 服务器。

我可以暂时删除 server 上的 connection 事件监听器,或者只通过调用 once 来设置它一次on,但是在没有 connection 事件监听器的情况下建立的任何连接似乎都丢失了。从 strace 中,我可以看到 Node 仍在套接字上 accept(2)ing。是否有可能让它不这样做,以便内核将所有传入请求排队,直到服务器准备好再次接受它们(或在 listen(2 ) 超出)?

示例代码无法正常工作:

#!/usr/bin/node
const net = require("net");
const server = net.createServer();
function onConnection(socket) {
socket.on("close", () => server.once("connection", onConnection));
let count = 0;
socket.on("data", (buffer) => {
count += buffer.length;
if (count >= 16) {
socket.end();
}
console.log("read " + count + " bytes total on this connection");
});
}
server.once("connection", onConnection);
server.listen(8080);
  1. 连接到 localhost,端口 8080,使用您选择的代理(ncsocattelnet ,……)。
  2. 发送少于 16 个字节,并见证服务器登录到终端。
  3. 在不杀死第一个代理的情况下,在另一个终端中进行第二次连接。尝试发送任意数量的字节——服务器不会记录任何内容。
  4. 在第一个连接上发送更多字节,以便发送的字节总数超过 16。服务器将关闭此连接(并再次将其记录到控制台)。
  5. 在第二个连接上发送更多字节。什么都不会发生。

我希望第二个连接阻塞,直到第一个连接结束,然后才能正常处理。这可能吗?

最佳答案

.. so that the kernel will instead queue up all incoming request until the server is ready to accept them again (or the backlog configured in listen(2) is exceeded)? ... I would like the second connection to block until the first one is over, and then to be handled normally. Is this possible?

不幸的是,如果不捕获发送的连接事件并在您的应用程序中管理已接受的连接而不是操作系统积压是不可能的。 Node 使用 OnConnection 回调调用 libuv,该回调将 try to accept所有连接并使它们在 JS 上下文中可用。

关于javascript - 是否可以暂停/挂起(不要在套接字上接受(2))Node.js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41232340/

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