如何发送可变长度的结构 [英] How to send a variable -length structure

查看:72
本文介绍了如何发送可变长度的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构:

I have a structure:

typedef struct{
    int flags;/*the type of message*/
    int length;/*the length of message*/
    void* message;/*the message*/
}Message;



消息的长度是可变的.例如:



The length of message is variable.For example:

Message msg;
msg.flags=0;
char buf[]="abcdef";
msg.length=strlen(buf);
msg.message=buf;



如何使用套接字将结构从客户端发送到服务器?有人帮我!或给我一些建议.



How can i send the structure from client to the server with socket? Someone help me!or give me some advisements.

推荐答案

数据在内存中的二进制表示形式以及您写入流中的序列化二进制形式(例如,文件流,管道流或由套接字支持的网络流)通常是不同的.
您对可变长度字符串的序列化以及连接另一侧的反序列化感到好奇.简单:
首先,将字符串的长度发送到套接字(例如,作为int32),然后发送字符串数据本身.在连接的另一端,您将长度读出到变量中,然后知道字符串有多长,以及要读取到字符串中的字节数.
The binary representation of your data in memeory and its serialized binary form that you write into stream (for example to a filestream, or pipe stream, or into a network stream backed by sockets) are often different.
You are curious about the serialization of your variable length string and about its deserialization on the other side of the connection. Its simple:
First you send the length of the string to your socket (for example as an int32) then you send the string data itself. On the other side of the connection you read out the length into a variable, and then you know how long the string is and how many bytes to read into your string.


这篇关于如何发送可变长度的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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