pause/suspend(不要在套接字上接受(2))一个Node.js服务器是可能的吗?
Is it possible to pause/suspend (don’t accept(2) on the socket) a Node.js server?
目标:拥有一台 Node.js 服务器,一次只有一个连接处于活动状态。
我可以暂时删除 server
上的 connection
事件侦听器,或者首先通过调用 once
而不是 on
只设置一次,但是在没有 connection
事件侦听器的情况下建立的任何连接似乎都丢失了。从 strace
,我可以看到 Node 仍在 accept(2)
ing 在套接字上。是否有可能让它不这样做,以便内核将所有传入请求排队,直到服务器准备好再次 accept
它们(或超过 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);
- 使用您选择的代理(
nc
、socat
、telnet
、...)连接到 localhost
、端口 8080。
- 发送少于16个字节,并见证服务器记录到终端。
- 在不杀死第一个代理的情况下,在另一个终端中进行第二次连接。尝试发送任意数量的字节——服务器不会记录任何内容。
- 在第一个连接上发送更多字节,以便发送的字节总数超过 16。服务器将关闭此连接(并再次将其记录到控制台)。
- 在第二个连接上发送更多字节。什么都不会发生。
我希望第二个连接阻塞,直到第一个连接结束,然后才能正常处理。这可能吗?
.. 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?
不幸的是,如果不捕获发送的连接事件并在您的应用程序中管理接受的连接而不是 OS 积压,则不可能。节点使用 OnConnection 回调调用 libuv,该回调将 try to accept 所有连接并使它们在 JS 上下文中可用。
目标:拥有一台 Node.js 服务器,一次只有一个连接处于活动状态。
我可以暂时删除 server
上的 connection
事件侦听器,或者首先通过调用 once
而不是 on
只设置一次,但是在没有 connection
事件侦听器的情况下建立的任何连接似乎都丢失了。从 strace
,我可以看到 Node 仍在 accept(2)
ing 在套接字上。是否有可能让它不这样做,以便内核将所有传入请求排队,直到服务器准备好再次 accept
它们(或超过 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);
- 使用您选择的代理(
nc
、socat
、telnet
、...)连接到localhost
、端口 8080。 - 发送少于16个字节,并见证服务器记录到终端。
- 在不杀死第一个代理的情况下,在另一个终端中进行第二次连接。尝试发送任意数量的字节——服务器不会记录任何内容。
- 在第一个连接上发送更多字节,以便发送的字节总数超过 16。服务器将关闭此连接(并再次将其记录到控制台)。
- 在第二个连接上发送更多字节。什么都不会发生。
我希望第二个连接阻塞,直到第一个连接结束,然后才能正常处理。这可能吗?
.. 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?
不幸的是,如果不捕获发送的连接事件并在您的应用程序中管理接受的连接而不是 OS 积压,则不可能。节点使用 OnConnection 回调调用 libuv,该回调将 try to accept 所有连接并使它们在 JS 上下文中可用。