QTcpSocket à QThread
-
20-09-2019 - |
Question
Je simple fil de connexion au serveur. Lorsque vous appelez la fonction receiveString, elle échoue. Toutefois, lorsque vous exécutez le code même en run (), il réussit. Ce qui est nécessaire pour la fonction receiveString au travail?
Je l'ai essayé à la fois
bool TestServerThread::receiveString(QTcpSocket& sock, QString& str)
bool TestServerThread::receiveString(QTcpSocket* sock, QString& str)
Code actuel:
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();
}
La solution
Soit votre code ruiné la pile de processus, ou votre valeur de délai d'attente ne suffit pas.
Autres conseils
Quelle est la valeur de retour ou QTcpSocket::errorString()
?
//...
if(!sock.waitForReadyRead(30))
{
qWarning() << "fails " << sock.errorString(); // fails here
emit error(sock.error());
return false;
}
//...
Notez que dans la course, vous lisez toujours les données sur la prise, même si QTcpSocket::waitForReadyRead
retourne faux.
Êtes-vous sûr que vous ne recevez pas la même erreur dans le run
comme dans receiveString
, mais la lecture réussit parce que vous ignorez cette erreur?
est run
encore réussit si vous utilisez ce 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;
}
}