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++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01