@@ -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 {
0 commit comments