以一种成功连接的tls.connect
实例应该解决的方式宣传socket
方法的正确方法是什么。我发现它有点棘手,因为似乎没有办法开箱即用,以区分连接时的错误和与TCP服务器通信期间的常规错误(成功连接后)。虽然看起来有些臭,但可能就像
const connect = (port, host, options) => {
/**
* Some workaround to be able
* to distinguish between error on connection
* and error after connection was established successfully
*/
let connected = false
return new Promise((resolve, reject) => {
const socket = tls.connect(port, host, options, () => {
connected = true
return resolve(socket)
})
socket.on('data', (data) => {...})
socket.on('end', () => {...})
socket.on('disconnect', () => {...})
socket.on('error', (err) => {
if (!connected) {
return reject(err)
}
console.error(err)
})
})
}
答案 0 :(得分:0)
立即返回套接字并向套接字添加connected
承诺 - 这样您可以同步附加其他处理程序并仍然听取与承诺的连接:
const connect = (port, host, options) => {
let resolve, reject;
var connected = new Promise((res, rej) => { resolve = res; reject = rej; });
const socket = tls.connect(port, host, options, resolve);
socket.connected = connected;
socket.on('error', reject); // it's fine to calll reject/resolve several times
return socket;
};