[Solved] Bidirectional communication between Client and Server by QTcpSocket



  • Hi again,

    I am able to communicate from client to server by
    @
    SERVER:
    listen(QHostAddress("localhost"),8888);
    connect(this, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
    ....
    void myServer::acceptConnection()
    {
    m_currnetClient = nextPendingConnection();

    connect(m_currnetClient, SIGNAL(readyRead()), this, SLOT(startRead()));
    }
    ....
    void myServer::startRead()
    {
    QString p_Line;
    p_Line = QString::fromUtf8(m_currnetClient->readLine()).trimmed();

    if(p_Line.mid(0,4)=="LOAD")
    {
    p_Line = QString::fromUtf8(m_currnetClient->readLine()).trimmed();
    unsigned int p_Result = _do_something_timeconsuming(p_Line.toStdString());
    if(p_Result==EXIT_SUCCESS)
    m_currnetClient->write("EXIT_SUCCESS\n");
    else
    m_currnetClient->write("EXIT_FAILURE\n");

    }
    }

    CLIENT:
    connectToHost(QHostAddress("localhost"), 8888);
    ....
    unsigned int myClient::_do_something(std::string i_ProjectFilename)
    {
    // Going to load mode
    write("LOAD\n");

    // sending filename
    write(i_ProjectFilename.c_str());

    // wait for result
    QString p_Line;
    p_Line = QString::fromUtf8(readLine()).trimmed();
    printf("-->%s<--\n",p_Line.toStdString().c_str());
    if(p_Line=="EXIT_SUCCESS")
    return EXIT_SUCCESS;
    else
    return EXIT_FAILURE;
    @

    So, the server really gets the LOAD command, then receivers the filename correctly, and executes "do_something".

    The result of this funtion is what I would like to return to the client. I thought about writing a line directly to the server the other way around, but the client one printfs "--><--", id est an empty line.

    What do I do wrong?


  • Lifetime Qt Champion

    Hi,

    Technically, you are not waiting for the result. You might use waitForReadyRead to really wait for something to have arrived.



  • Hi,

    thanks, that was exactly what I was searching for. It works.

    Maybe an add question:

    How do I have to modify to send a std::vector<float> instread of a QString?
    each float independently does not seem to be efficient.

    regards,
    curator


  • Lifetime Qt Champion

    You can use a QDataStream to prepare your data to send.

    Don't forget to send the size of the vector to read the right amount of data on the other end.



  • Hi, that solved at least by part my Problem. As the next is kind of different, I start a new post.

    Thank you,
    curator


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.