通过TCP发送结构(C编程) [英] Sending struct over TCP (C-programming)

查看:128
本文介绍了通过TCP发送结构(C编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端和服务器程序,我想从客户端发送整个结构,然后在服务器上输出结构成员"ID".

I have a client and server program where I want to send an entire struct from the client and then output the struct member "ID" on the server.

我已经完成了所有的连接操作,并且已经设法通过以下方式发送了字符串:

I have done all the connecting etc and already managed to send a string through:

send(socket, string, string_size, 0);

那么,是否可以通过send()发送结构而不是字符串?我可以将服务器上的缓冲区替换为相同类型的空结构然后继续吗?

So, is it possible to send a struct instead of a string through send()? Can I just replace my buffer on the server to be an empty struct of the same type and go?

推荐答案

Well,...如果做得正确,很难通过网络发送结构.

Welll... sending structs through the network is kinda hard if you are doing it properly.

卡尔是对的-您可以通过网络发送结构,方法是:

Carl is right - you can send a struct through a network by saying:

send(socket, (char*)my_struct, sizeof(my_struct), 0);

但是这是东西:

  • sizeof(my_struct)可能在客户端和服务器之间更改.编译器通常会进行一些填充和对齐,因此,除非您明确定义对齐方式(也许使用#pragma pack()),否则大小可能会有所不同.
  • 另一个问题往往是字节顺序的.有些机器是大端的,而其他机器是小端的,因此字节的排列可能会有所不同.实际上,除非您的服务器或客户端在非Intel硬件上运行(可能不是这种情况),否则从理论上讲,这个问题比实际存在的更多.

因此,人们通常建议的解决方案是拥有一个序列化该结构的例程.也就是说,它一次发送一个struct数据成员,以确保客户端和服务器仅将您编码到程序中的字节数指定为send()和recv().

So the solution people often propose is to have a routine that serializes the struct. That is, it sends the struct one data member at a time, ensuring that the client and server only send() and recv() the exact specified number of bytes that you code into your program.

这篇关于通过TCP发送结构(C编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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