QThread中的QTcpSocket

时间:2009-10-09 12:56:01

标签: multithreading qt qthread

我有简单的服务器连接线程。当你调用函数receiveString时,它会失败。但是,当您在run()中执行相同的代码时,它会成功。函数receiveString需要什么才能工作?

我试过了两次

bool TestServerThread::receiveString(QTcpSocket& sock, QString& str)
bool TestServerThread::receiveString(QTcpSocket* sock, QString& str)

实际代码:

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();
}

2 个答案:

答案 0 :(得分:2)

您的代码破坏了进程堆栈,或者您的超时值不够。

答案 1 :(得分:1)

返回值是什么?QTcpSocket::errorString()

//...
if(!sock.waitForReadyRead(30))
{
    qWarning() << "fails " << sock.errorString(); // fails here
    emit error(sock.error());
    return false;
}
//...

请注意,在运行中,即使QTcpSocket::waitForReadyRead返回false,您也始终在读取套接字上的数据。 您确定run中的错误与receiveString中的错误相同,但读取成功是因为您忽略了此错误吗?

如果您使用此代码,run仍然成功:

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;
    }
}