C++ 如何通过套接字发送对象?

2021-12-28 00:00:00 sockets recv tcp c++ send

我有个问题想问你.

我有这门课:

`

#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];
}

`

并且该应用程序有一个客户端和一个服务器.在我的服务器的主体中,我以这种方式实例化了这个类的一个对象:块 a(1);

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?

推荐答案

从字面意义上讲,通过 TCP 连接发送对象是不可能的.套接字只知道如何传输和接收字节流.所以你可以做的是通过 TCP 连接发送一系列字节,格式设置为接收程序知道如何解释它们并创建一个与发送程序想要发送的对象相同的对象.

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.

该过程称为序列化(以及接收方的反序列化).序列化不是内置在 C++ 语言本身中的,因此您需要一些代码来完成它.它可以手动完成,或使用 XML,或通过 Google 的协议缓冲区,或通过将对象转换为人类可读的文本并发送文本,或任何其他方式.

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.

查看此处了解更多信息.

相关文章