Skip to content

Commit fc7654e

Browse files
committed
Add timeout for TCP connection
1 parent 43848b1 commit fc7654e

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/client.cpp

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,20 +267,40 @@ void CClient::OnSendCLProtMessage ( CHostAddress InetAddr, CVector<uint8_t> vecM
267267
// create a TCP client connection and send message
268268
QTcpSocket* pSocket = new QTcpSocket ( this );
269269

270+
// timer for TCP connect timeout shorter than Qt default 30 seconds
271+
QTimer* pTimer = new QTimer ( this );
272+
pTimer->setSingleShot ( true );
273+
274+
connect ( pTimer, &QTimer::timeout, this, [this, pSocket, pTimer]() {
275+
if ( pSocket->state() != QAbstractSocket::ConnectedState )
276+
{
277+
pSocket->abort();
278+
pSocket->deleteLater();
279+
qDebug() << "- TCP connect timeout";
280+
}
281+
pTimer->deleteLater();
282+
} );
283+
270284
#if QT_VERSION >= QT_VERSION_CHECK( 5, 15, 0 )
271285
# define ERRORSIGNAL &QTcpSocket::errorOccurred
272286
#else
273287
# define ERRORSIGNAL QOverload<QAbstractSocket::SocketError>::of ( &QAbstractSocket::error )
274288
#endif
275-
connect ( pSocket, ERRORSIGNAL, this, [this, pSocket] ( QAbstractSocket::SocketError err ) {
289+
connect ( pSocket, ERRORSIGNAL, this, [this, pSocket, pTimer] ( QAbstractSocket::SocketError err ) {
276290
Q_UNUSED ( err );
277291

292+
pTimer->stop();
293+
pTimer->deleteLater();
294+
278295
qWarning() << "- TCP connection error:" << pSocket->errorString();
279296
// may want to specifically handle ConnectionRefusedError?
280297
pSocket->deleteLater();
281298
} );
282299

283-
connect ( pSocket, &QTcpSocket::connected, this, [this, pSocket, InetAddr, vecMessage, eProtoMode]() {
300+
connect ( pSocket, &QTcpSocket::connected, this, [this, pSocket, pTimer, InetAddr, vecMessage, eProtoMode]() {
301+
pTimer->stop();
302+
pTimer->deleteLater();
303+
284304
// connection succeeded, give it to a CTcpConnection
285305
CTcpConnection* pTcpConnection = new CTcpConnection ( pSocket,
286306
InetAddr,
@@ -299,6 +319,7 @@ void CClient::OnSendCLProtMessage ( CHostAddress InetAddr, CVector<uint8_t> vecM
299319
} );
300320

301321
pSocket->connectToHost ( InetAddr.InetAddr, InetAddr.iPort );
322+
pTimer->start ( TCP_CONNECT_TIMEOUT_MS );
302323
}
303324
else
304325
{

src/tcpconnection.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
class CServer; // forward declaration of CServer
4141
class CChannel; // forward declaration of CChannel
4242

43+
#define TCP_CONNECT_TIMEOUT_MS 3000
4344
#define TCP_KEEPALIVE_INTERVAL_MS 15000
4445

4546
/* Classes ********************************************************************/

0 commit comments

Comments
 (0)