c++ - Making a client in Qt that tries to connect to server, and if it fails, it keeps trying until it connects -
i'm using qtcpsocket program.
void mainwindow::connectfunction() { socket->connecttohost(ip, port); if(socket->waitforconnected(2000)) { qtime time = qtime().currenttime(); ui->textbrowser->append('[' + time.tostring("h:m") + "] connection successful."); } else { qtime time = qtime().currenttime(); ui->textbrowser->append('[' + time.tostring("h:m") + "] connection failed. retrying..."); connectfunction(); } } i attempt connect server ui->connecttohost(ip, port). if connection fails, call connectfunction() again restart connecting process. should until connection successful. problem arises when call connectfunction(). crashes program, , don't know why. appreciated.
the problem calling connectfunction recursively , if connection fails many iterations, encounter stack-overflow error. 1 alternate solution have connectfunction slot , call in queued way prevent recursion:
void mainwindow::connectfunction() { socket->connecttohost(ip, port); if(socket->waitforconnected(2000)) { qtime time = qtime().currenttime(); ui->textbrowser->append('[' + time.tostring("h:m") + "] connection successful."); } else { qtime time = qtime().currenttime(); ui->textbrowser->append('[' + time.tostring("h:m") + "] connection failed. retrying..."); qmetaobject::invokemethod(this, "connectfunction", qt::queuedconnection ); } } there other possible solutions implementing in asynchronous way , starting timer invokes connecting periodically when error occurred.
Comments
Post a Comment