Hi, I’m Shendi
Nodejs中net模块多次Socket.setTimeout无法覆盖之前函数,导致叠加执行问题解决
问题描述
在 Nodejs 中,net
模块的 Socket
的 setTimeout 函数是设置超时时间,如果多次设置,超时时间会是最后一次的时间,但设置的函数会叠加执行,例如如下代码
const server = net.createServer((socket) => {
socket.setTimeout(2000, () => {
console.log('Socket timeout after 2 seconds');
});
socket.setTimeout(5000, () => {
console.log('Socket timeout after 5 seconds');
});
socket.setTimeout(10000, () => {
console.log('Socket timeout after 10 seconds');
});
});
server.listen(8080, () => {
console.log('Server listening on port 8080');
});
const client = new net.Socket();
client.connect(8080, 'localhost', () => {
console.log('Connected to server');
});
执行后会发现,10秒后,设置的函数都被执行了。
问题解决
通过查看Socket.setTimeout
的注释,有如下描述
The optional callback parameter will be added as a one-time listener for the ‘timeout’ event.
即,同 on
添加监听,那么可以通过移除监听来解决
有两种方式,一种移除指定监听的单个监听,这种需要将函数保存起来,一种是移除指定监听的所有监听
对于我的需求,只需要保留最后一次设置,那么使用移除所有就可以了
代码如下
const server = net.createServer((socket) => {
socket.setTimeout(2000, () => {
console.log('Socket timeout after 2 seconds');
});
socket.setTimeout(5000, () => {
console.log('Socket timeout after 5 seconds');
});
socket.removeAllListeners("timeout");
socket.setTimeout(10000, () => {
console.log('Socket timeout after 10 seconds');
});
});
server.listen(8080, () => {
console.log('Server listening on port 8080');
});
const client = new net.Socket();
client.connect(8080, 'localhost', () => {
console.log('Connected to server');
});
输出如下
END