How can you send complex objects with sockets?



  • hello to the whole community Qt Forum,
    I have a question, I'm developing a client / server application and I would like to know if there are socket (qt) functions capable of sending complex objects of variable size, but note when sending.
    Obviously the receiver will also know the size;
    Thanks in advance


  • Qt Champions 2018

    Hi @danga96,

    you should look up QDataStream which allows exactly this.

    Regards


  • Qt Champions 2018

    Another alternative is to use JSON or the more recently added CBOR directly on the device



  • @aha_1980
    Thank you for your reply; only that I need to send an object through a socket, not through a file ... I know they are very similar, but I would like to find, a class that does this right :)



  • @danga96 said in How can you send complex objects with sockets?:

    I need to send an object through a socket, not through a file

    #include <QCoreApplication>
    #include <QDebug>
    #include <QDataStream>
    #include <QByteArray>
    
    struct complex_object{
        QString m_string;
        float m_float;
        int m_int;
    };
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        complex_object cp;
        cp.m_string = "Some 💩";
        cp.m_float = 0.666;
        cp.m_int = 42;
    
        qInfo() << "before send:" << cp.m_string << cp.m_float << cp.m_int;
    
        QByteArray data; // used by socket stuff to hold data
        QDataStream sdata(&data, QIODevice::WriteOnly);
        sdata << cp.m_string << cp.m_float << cp.m_int;
    
        qInfo() << "... magically floating through cyberspace via sockets";
    
        complex_object cp2;
        QDataStream rdata(&data, QIODevice::ReadOnly);
        rdata >> cp2.m_string >> cp2.m_float >> cp2.m_int;
    
        qInfo() << "after receive:" << cp2.m_string << cp2.m_float << cp2.m_int;
    
        return a.exec();
    }
    

    I like puppies and kittens... (reference to show that describes "knowing your place", and yes, totally random)


  • Qt Champions 2018

    @danga96

    Thank you for your reply; only that I need to send an object through a socket, not through a file

    Everything is a file in Unix, and everything a QIODevice in Qt.

    Regards



  • @aha_1980 said in How can you send complex objects with sockets?:

    Everything is a file in Unix, and everything a QIODevice in Qt.

    So say we all...


Log in to reply
 

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