如何使用 sendto() 发送结构
我已经创建了结构:
struct buffer
{
string ProjectName ;
string ProjectID ;
}
buffer buf;
buf.ProjectID = "212";
buf.ProjectName = "MyProj";
现在要使用 sendto 方法发送此结构,我正在对结构进行类型转换并将其发送回,如下所示:
char *sendbuf = (char*)&buf;
sentbytes = sendto(sock,sendbuf,strlen(sendbuf),0,(sockaddr*)&their_addr,sizeof(their_addr));
但是当我转换结构 ti char*
时,实际数据正在丢失它的值在调试时我看到 sendbuf 包含一些其他值。
有人可以告诉我如何使用 sendto 发送上述结构吗?
I have created structure :
struct buffer
{
string ProjectName ;
string ProjectID ;
}
buffer buf;
buf.ProjectID = "212";
buf.ProjectName = "MyProj";
Now to send this structure using sendto method , I am typecasting the strucure and sending it back as below:
char *sendbuf = (char*)&buf;
sentbytes = sendto(sock,sendbuf,strlen(sendbuf),0,(sockaddr*)&their_addr,sizeof(their_addr));
But while I am casting my Struct ti char*
the actual data is loosing it's values and while debugging I see sendbuf is containing some other values.
Can some one let me know how can I send the above structure using sendto.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用 POD 创建结构,字符串不能以这种方式使用。相反,您需要声明它,例如
编辑:澄清,该字符串包含指向堆分配的内存块的指针,因此当您尝试发送该结构时,您实际上并没有发送字符。
You need to create the structure using POD, the string is not something you can use in that way. Instead you need to declare it something like
EDIT: clarification, the string contains a pointer to a heap allocated memory block, so you are not actually sending the characters when you try to send that structure.
std::string
将其数据保存在动态分配的内存中。您可以单独发送每个字符串和字符串的长度,您可以使用 std::string::c_str 和 std::string::size 获得。std::string
holds its data in dynamically allocated memory. You could send separately each string and length of a string which you can get by usingstd::string::c_str
andstd::string::size
.通过网络发送数据时更喜欢使用编组/解组。 C++ 风格是使用“<< / >>”用于流式传输到可发送缓冲区。这样,您就可以更好地控制发送内容以及发送方式(二进制、文本、xml...)。 Boost 还有一个序列化模块。
Prefer using marshall/unmarshall when sending data over network. A C++-style is to use "<< / >>" for streaming to a sendable buffer. This way, you have more control over what you are sending and how it is sent (binary,text,xml,...). Boost also has a serialization module.