PDA

View Full Version : QTcpSocket in QThread



zverj
12th October 2009, 10:04
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();
}


When you subclass QTcpSocket - same error results
sock.errorString() returns "Network operation timed out" in function receiveString(). In run() it succeeds

zverj
12th October 2009, 10:27
My stupid mistake of timeout too low.