Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QT an QTcpSocket



  • Hi!
    I have very important question. I have used QT to programming very simple TCP server - I want that client gets two variables: x and y and send it to server ant it should sum them and return this sum to client. My code is very similar to Threated Fortune Server & Fortune Client. However, I change method "run" in fortunethread.h to

    @
    ...

    void FortuneThread::run()
    {
    //emit msgSignal(QString::number(socketDescriptor));
    readFromSocket();
    }

    void FortuneThread::readFromSocket()
    {
    //QString numbers;

        QTcpSocket tcpSocket;
    
        if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
         emit error(tcpSocket.error());
         return;
     }
    
    
         if(tcpSocket.isReadable()) //(1)
         {
                QDataStream in(&tcpSocket);
                in.setVersion(QDataStream::Qt_4_0);
    
                QString numbers;
    
                QByteArray arr;
    
                in >> arr;
    
                QString k (arr.data());
    

    --
    //this signal opened QMessageBox with message in parameter
    emit msgSignal("Deskryptor: " + QString::number(socketDescriptor) + "\nDane: " + k);
    }
    else
    {
    emit msgSignal("asdfghjklasdfghjkl");
    }

        tcpSocket.disconnectFromHost();
        tcpSocket.waitForDisconnected();
    

    }

    ...

    @

    and cliend should send data to server (after press getFortuneButton):

    @
    void Client::writeToSocket(){

                tcpSocket->connectToHost(hostLineEdit->text(),
                                                                 portLineEdit->text().toInt());        
    
                QString num = (x + " " + y);
                QByteArray tab = num.toAscii();
    
                // QMessageBox b;
                // b.setText(x + " + " + y);
                // b.exec();
    
                tcpSocket->write(tab);
                tcpSocket->disconnectFromHost();
                tcpSocket->close();
    

    }

    @

    Why it isn't work?? Thanks for help :D



  • QTcpSocket has asynchronious model of work. Send data after connection will be established.


Log in to reply