Skip to content

Commit e9834da

Browse files
committed
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
1 parent f79a044 commit e9834da

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/transport/tcp/tcpConnection.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,11 +153,22 @@ TcpConnection.createConnectingConnection = function(
153153
connection._initSocket(socket);
154154
if (onConnectionEstablished) onConnectionEstablished(connection);
155155
});
156+
var timer = setTimeout(function(){
157+
log.error('TcpConnection: timeout when connecting to %j in %d ms', remoteEndPoint, connectionTimeout);
158+
connection.close();
159+
if (onConnectionFailed) onConnectionFailed(connection, new Error('Connection failed'));
160+
}, connectionTimeout)
156161
socket.once('error', onError);
157162
function onError(err) {
163+
clearTimeout(timer);
158164
if (onConnectionFailed) onConnectionFailed(connection, err);
159165
}
166+
socket.once('connect', onConnect);
167+
function onConnect() {
168+
log.info('TcpConnection: successfully connected to %j', remoteEndPoint);
169+
clearTimeout(timer);
170+
}
160171
return connection;
161172
};
162173

163-
module.exports = TcpConnection;
174+
module.exports = TcpConnection;

0 commit comments

Comments
 (0)