C++ How can I send an object via socket?(C++ 如何通过套接字发送对象?)
问题描述
我有个问题想问你.
我有这门课:
`
#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.
查看此处了解更多信息.
这篇关于C++ 如何通过套接字发送对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 如何通过套接字发送对象?


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01