序列化和反序列化插座中的结构 [英] serialize and deserialize structures in sockets

查看:122
本文介绍了序列化和反序列化插座中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Struct通过套接字发送到客户端。客户端和服务器都在同一个架构上,因此没有端点问题。我正确地接收int值。但不能正确接收char []值。
这是结构。

I have a Struct to send over a socket to a client. Both the Client and the Server is on the same architecture so there is no endian problem. I receive the int values properly. But not able to receive the char[] values properly. This is the structure.

struct Packet {
int id;
int number;
char data[256];
};

在服务器端我序列化数据并写入客户端。

In the Server side I serialize the data and write to the client.

struct Packet *s = new Packet();
s->id= htonl(1000);
s->number= htonl(7788);
memcpy(s->data, "MESSAGE", 7);

n =  write(NewSockFD , s ,sizeof(s) );

在客户端,我反序列化数据。

In the Client side I deserialize the data.

n = read(SockFD , Buffer , sizeof(Buffer));
struct Packet *s = (struct Packet*)Buffer;
char b[256];
int i = ntohl(s->id);
int j = ntohl(s->number);
memcpy(b, s->data, sizeof(s));

我正确接收到id和数值。问题是与数据值。我在这里做错了。

I receive the id and number values correctly. Problem is with the data value. What I'm doing wrong here??..

推荐答案

在你的代码中,你使用 sizeof s)。这将是 Packet * 的大小,而不是数据包的大小。替换为 sizeof(* s)以获得正确的大小。

In your code, you use sizeof(s). This will be the size of a Packet*, not a Packet. Replace it with sizeof(*s) to get the correct size.

c $ c> data 不是都被初始化,你通过读取它导致未定义的行为。你需要以一种方式或另一种方式初始化所有元素(最简单的方法是在结构体定义中执行 char data [256] {}; )。

Additionally, since the values of data are not all initialised, you cause undefined behaviour by reading from it. You need to initialise all the elements one way or the other (the shortest way would be to do char data[256] { }; in the struct definition).

也因为这是C ++,你不需要说 struct Packet ,你可以说 Packet ,除非你还有一个名为 Packet 的函数。

Also since this is C++, you don't need to say struct Packet, you can say just Packet, unless you also have a function named Packet. But it appears in your code only half the time which means you don't, so you can just drop it.

正如Chris G所说,你还有另外一个问题,在你的代码中只有一半的时间,这意味着你不会,你修复了,这是你把一个数据包复制到 char [] a 数据包数据。更改

And as Chris G mentioned, you have another problem after you fix that, which is that you're copying an entire Packet into a char[] only big enough to hold a Packet's data. Change

memcpy(b, s->data, sizeof(s))

memcpy(b, s->data, sizeof(s->data))

如果发件人没有为您(您可能需要采取预防措施),c> data 可能不会被终止。

And realise that this data may not be nul-terminated if the sender didn't do it for you (which you may want to take precautions against).

这篇关于序列化和反序列化插座中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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