Pregunta

Tengo sencilla rosca de conexión del servidor. Cuando se llama a la función receiveString, falla. Sin embargo, cuando se ejecuta en el mismo código run (), tiene éxito. Lo que se necesita para receiveString función para trabajar?

He intentado tanto

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

código real:

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();
}
¿Fue útil?

Solución

Puede ser que su código arruinó la pila de proceso, o el valor de tiempo de espera no es suficiente.

Otros consejos

¿Cuál es el valor de retorno o QTcpSocket::errorString()?

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

Tenga en cuenta que en el período previo, siempre leyendo los datos sobre la toma de corriente, incluso si QTcpSocket::waitForReadyRead volvió falsa.
¿Seguro que no recibe el mismo error en el run como en receiveString, pero la lectura tiene éxito porque se ignora este error?

¿Se run sigue teniendo éxito si se utiliza este código:

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;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top