gpt4 book ai didi

node.js - Node net socket.end 事件触发两次?

转载 作者:太空宇宙 更新时间:2023-11-04 00:23:23 24 4
gpt4 key购买 nike

This event发射两次。我正在尝试找出原因。

在一个客户端上,我有:

import Net from 'net';
import Chalk from 'chalk';

const fallback = [2,5,10,25,50,100,250,500,1000,2000];

class LocalNetworkInterface {

constructor({path}) {
this._sock = new Net.Socket();
this._pending = {};
this._count = 0;
this._retry = 0;

const connect = () => {
this._sock.connect({path});
};
this._sock.on('connect',() => {
this._retry = 0;
console.log(`Connected to ${Chalk.underline(path)}`);
});
this._sock.on('data',buffer => {
let data = JSON.parse(buffer);
this._pending[data.queryId].resolve(data);
delete this._pending[data.queryId];
});
this._sock.on('end', () => {
console.log(`Lost connection to ${Chalk.underline(path)}. Attempting to reconnect...`);
connect();
});
this._sock.on('error', err => {
if(err.code === 'ENOENT') {
let ms = fallback[this._retry];
if(this._retry < fallback.length - 1) ++this._retry;
console.log(`Socket server unavailable. Trying again in ${ms}ms`);
setTimeout(connect, ms);
}
});
connect();
}

// ...
}

服务器:

const sockServer = Net.createServer(c => {
c.on('data', buffer => {
let data = JSON.parse(buffer);
// log('Received',data);
let ql = queryLogger();
runQuery(Object.assign({}, data, {schema})).then(result => {
ql(`${Chalk.magenta('socket')} ${print(data.query).trim()}`);
let response = Object.assign({}, result, {queryId: data.queryId});
c.write(JSON.stringify(response));
});
})
});

sockServer.on('error', serverError => {
if(serverError.code === 'EADDRINUSE') {
let clientSocket = new Net.Socket();
clientSocket.on('error', clientError => {
if(clientError.code === 'ECONNREFUSED') {
FileSystem.unlink(SOCK_FILE, unlinkErr => {
if(unlinkErr) throw unlinkErr;
sockServer.listen(SOCK_FILE, () => {
log(`Sock server improperly shut down. Listening on '${sockServer.address()}'`)
});
});
}
});
clientSocket.connect({path: SOCK_FILE}, () => {
throw new Error(`Server already running`);
});
}
});

['SIGTERM','SIGINT'].forEach(signal => process.on(signal, () => {
console.log(`\rReceived ${Chalk.yellow(signal)}, shutting down ${Chalk.red('❤')}`);
sockServer.close();
process.exit();
}));

sockServer.listen(SOCK_FILE, () => {
log(`Listening on ${Chalk.underline(sockServer.address())}`)
});

当我重新启动服务器时,我在客户端上看到两次“丢失连接”。为什么?

文档说:

Emitted when the other end of the socket sends a FIN packet.

服务器没有发送两个“FIN”数据包,是吗?有什么办法可以验证吗?

最佳答案

docs 中看到此内容关于连接...

“...此函数是异步的。当发出“connect”事件时,套接字就会建立。如果连接出现问题,则不会发出“connect”事件,将发出“error”事件,但会出现异常。”

事实上,connect 事件可能根本没有触发,只是让您看起来就像 end 事件触发了两次?就像 @robertklep 所说,也许可以将错误检查扩展到特定代码之外。

关于node.js - Node net socket.end 事件触发两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43744881/

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