定义网络通信的结构
Define structure for network communication in C
我想在C中定义一个用于网络传输的结构,例如,我想转移一个动物结构,该结构包含动物名称的可变长度。
afaik,一种方法是 using a predefined length of char array
或结构中的 using a buffer
,我们可以解析缓冲区(例如,第一个4个字节是动物名称长度,然后是动物名称,然后是其他领域的长度和其他字段其他字段的值),后一种方法的优点是它允许可变名称长度,如以下代码所示:
struct Animal
{
char name[128];
int age;
}
或:
struct Animal
{
int bufferLen;
char* pBuffer;
}
我的问题是:我的方法正确吗?即,有一些转移结构的标准方法,并且有更好的方法吗?
我的第二个问题是:我需要注意划桨,即使用#pragma pack(push/pop, n)
?
预先感谢!
两者都可以正常工作,但是,如果您使用固定的长度包装 sturct
,它使其更容易处理,但是您可能会发送比所需的更多数据,例如,假设A 4字节 Integer的代码将发送132
字节:
//packed struct
struct Animal {
char name[128];
int age;
};
Animal a = {"name", 2};
send(fd, &a, sizeof(a), 0);
//and you're done
另一方面,可变长度字段将需要更多的工作来分配内存和包装单个数据包,但是您将能够发送所需的确切字节数,在这种情况下,9
字节:
//not necessarily packed
struct Animal {
char *name;
int age;
};
//some arbitrary length
int name_length = 50;
//you should check the result of malloc
Animal a = {malloc(name_length), 2};
//copy the name
strcpy(a.name, "name");
//need to pack the fields in one buff
char *buf = malloc(strlen(a.name)+ 1 + sizeof(a.age));
memcpy(buf, a.name, strlen(a.name)+1);
memcpy(buf, &a.age, sizeof(a.age));
send(fd, buf, strlen(a.name)+ 1 + sizeof(a.age));
//now you have to do some cleanup
free(buf);
free(a.name);
编辑:当然,如果您想自己实施该库,则可以使用库为您序列化数据。另外,在Beej的网络编程指南中查看示例序列化代码
相关文章:
- 用于本地网络运行的客户端服务器体系结构
- 使用 UDP 协议从 Windows 套接字发送到 Qt 套接字的网络数据包上的结构编码和解码
- C 设计用于多层通信的软件体系结构
- 分解通信:传递C风格结构与C 对象
- 使用Boost.ASIO与服务器进行简单的网络tcp通信
- 定义网络通信的结构
- CAN-BUS通信-MSG结构(Winuser.h)Linux等效
- 通过网络发送 Python c_types结构
- 如何使用套接字构建健壮的网络体系结构
- 通过网络在应用程序之间进行通信
- C++/CLI(.NET)等效于将结构写入网络的本机C++
- stl或boost中是否存在用于线程间通信的线程安全结构,其行为类似于队列
- 用c++实现TCP/Ip网络通信
- Qt TCP/IP通信只能在本地工作,但在网络中会丢失
- 结构术语设置,用于与Arduino进行串行通信
- 具有进程间通信功能的服务器-客户端日志记录体系结构.你知道解决方案吗?
- Qt和Node JS通过WebSockets进行网络通信
- PLC和网络通信:概念基础
- 正在将C++结构转换为C#以用于UDP通信
- 用于通过网络在应用程序之间进行通信的协议/基础结构