From e9834daa3116ccf1c63887543ca8acd2b3eef355 Mon Sep 17 00:00:00 2001 From: maniolias Date: Thu, 17 Sep 2020 09:06:20 +0200 Subject: [PATCH] feat(tcp): add timeout when trying to connect to a TCP endpoint * the timeout parameters in options will trigger a timeout only when the socket is connected (cf. https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). To handle connection timeout we have to handle it manually --- src/transport/tcp/tcpConnection.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/transport/tcp/tcpConnection.js b/src/transport/tcp/tcpConnection.js index 1d2ab55..1326c49 100644 --- a/src/transport/tcp/tcpConnection.js +++ b/src/transport/tcp/tcpConnection.js @@ -153,11 +153,22 @@ TcpConnection.createConnectingConnection = function( connection._initSocket(socket); if (onConnectionEstablished) onConnectionEstablished(connection); }); + var timer = setTimeout(function(){ + log.error('TcpConnection: timeout when connecting to %j in %d ms', remoteEndPoint, connectionTimeout); + connection.close(); + if (onConnectionFailed) onConnectionFailed(connection, new Error('Connection failed')); + }, connectionTimeout) socket.once('error', onError); function onError(err) { + clearTimeout(timer); if (onConnectionFailed) onConnectionFailed(connection, err); } + socket.once('connect', onConnect); + function onConnect() { + log.info('TcpConnection: successfully connected to %j', remoteEndPoint); + clearTimeout(timer); + } return connection; }; -module.exports = TcpConnection; \ No newline at end of file +module.exports = TcpConnection;