Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a question for you.

I have this class:

`

#define DIMBLOCK 128
#ifndef _BLOCCO_
#define _BLOCCO_

class blocco
{
    public:
        int ID;
        char* data;


        blocco(int id);
};

#endif




blocco::blocco(int id)
{
    ID = id;
    data = new char[DIMBLOCK];
}

`

and the application has a client and a server. In the main of my server I instantiate an object of this class in this way: blocco a(1);

After that I open a connection between the client and the server using sockets. The question is: how can I send this object from the server to the client or viceversa? Could you help me please?

like image 394
rosekarma Avatar asked Aug 29 '13 16:08

rosekarma


2 Answers

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.

like image 175
Jeremy Friesner Avatar answered Oct 22 '22 15:10

Jeremy Friesner


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

like image 27
4pie0 Avatar answered Oct 22 '22 15:10

4pie0