C ++如何通过套接字发送对象? [英] C++ How can I send an object via socket?

查看:82
本文介绍了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];
}

`

,该应用程序有一个客户端和一个服务器.在服务器的主体中,我以这种方式实例化了此类的对象:blocco 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 ++如何通过套接字发送对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆