Domanda

Ho semplice filo di connessione al server. Quando si chiama la funzione receiveString, fallisce. Tuttavia, quando si esegue lo stesso codice a run (), riesce. Ciò che è necessario per la funzione receiveString a lavorare?

Ho provato sia

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

codice vero e proprio:

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();
}
È stato utile?

Soluzione

In entrambi il codice rovinato la pila processo, o il vostro valore di timeout non è sufficiente.

Altri suggerimenti

Qual è il valore di ritorno o QTcpSocket::errorString()?

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

Si noti che nella corsa, che si sta sempre leggendo i dati sul socket, anche se QTcpSocket::waitForReadyRead restituito falso.
Sei sicuro di non avere lo stesso errore nel run come in receiveString, ma la lettura riesce perché si ignora questo errore?

E 'ancora run successo se si utilizza questo codice:

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;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top