C++ How can I send an object via socket?

It's impossible to send objects across a TCP connection in the literal sense. Sockets only know how to transmit and receive a stream of bytes. So what you can do is send a series of bytes across the TCP connection, formatted in such a way that the receiving program knows how to interpret them and create an object that is identical to the one the sending program wanted to send.

That process is called serialization (and deserialization on the receiving side). Serialization isn't built in to the C++ language itself, so you'll need some code to do it. It can be done by hand, or using XML, or via Google's Protocol Buffers, or by converting the object to human-readable-text and sending the text, or any of a number of other ways.

Have a look here for more info.


you can do this using serialization. This means pulling object into pieces so you can send these elements over the socket. Then you need to reconstruct your class in the other end of connection. in Qt there is QDataStream class available providing such functionality. In combination with a QByteArray you can create a data package which you can send. Idea is simple:

Sender:

QByteArray buffer;
QDataStream out(&buffer);
out << someData << someMoreData;

Receiver:

QByteArray buffer;
QDataStream in(&buffer);
in >> someData >> someMoreData;

Now you might want to provide additional constructor:

class blocco
{
    public:
        blocco(QDataStream& in){
            // construct from QDataStream
        }

        //or
        blocco(int id, char* data){
            //from data
        }
        int ID;
        char* data;


        blocco(int id);
};

extended example