QTcpSocket in QThread
-
20-09-2019 - |
Question
I have simple server connection thread. When you call function receiveString, it fails. However when you execute same code in run(), it succeeds. What is needed for function receiveString to work?
I've tried both
bool TestServerThread::receiveString(QTcpSocket& sock, QString& str)
bool TestServerThread::receiveString(QTcpSocket* sock, QString& str)
Actual code:
TestServerThread::TestServerThread(int socketDescriptor, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor)
{
}
bool TestServerThread::receiveString(QTcpSocket& sock, QString& str)
{
if(sock.isValid())
{
if(!sock.waitForReadyRead(30))
{
qWarning() << "fail"; // fails here
return false;
}
QByteArray buf = sock.readAll();
str = buf;
}
}
void TestServerThread::run()
{
QTcpSocket sock;
if (!sock.setSocketDescriptor(socketDescriptor)) {
emit error(sock.error());
return;
}
bool ok = true;
while(ok)
{
QString str;
//if(ok) ok = receiveString(sock, str);
if(!sock.waitForReadyRead(30))
{
qWarning() << "false";
}
QByteArray buf = sock.readAll(); // same routine succeeds
str = buf;
qWarning() << str;
qWarning() << "Received: " << str;
if(ok) ok = sendString(sock, "kaka");
}
sock.disconnectFromHost();
sock.waitForDisconnected();
}
Solution
Either your code ruined the process stack, or your timeout value is not enough.
OTHER TIPS
What is the return value or QTcpSocket::errorString()
?
//...
if(!sock.waitForReadyRead(30))
{
qWarning() << "fails " << sock.errorString(); // fails here
emit error(sock.error());
return false;
}
//...
Note that in the run, you are always reading the data on the socket, even if QTcpSocket::waitForReadyRead
returned false.
Are you sure you don't get the same error in the run
as in receiveString
, but the read succeeds because you ignore this error?
Is run
still succeeding if you use this code:
bool ok = true;
while(ok)
{
QString str;
//if(ok) ok = receiveString(sock, str);
if(sock.waitForReadyRead(30))
{
QByteArray buf = sock.readAll(); // same routine succeeds
str = buf;
qWarning() << str;
qWarning() << "Received: " << str;
if(ok)
{
ok = sendString(sock, "kaka");
}
}
else
{
qWarning() << "fails " << sock.errorString();
ok = false;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow