通过 Winsocks 发送 int 数组
我正在尝试通过 Winsocks 发送 int 数组。我可能是错的,但我很确定只支持 char*,所以我有点困惑如何正确地做到这一点。小/大edian也存在问题,那么有什么好的方法可以做到这一点呢?我已经问过 将 int array 转换为 char 的问题,但建议相反,请在网络部分启动一个新线程。
I'm trying to send an int array through Winsocks. I might be wrong, but I'm pretty sure only a char* is supported so I'm kind of stuck on how to do this properly. There are also problems with little/big edian, so what would be a good way to do this? I've already asked a question of converting int array to char but it was recommended to start a new thread on this in the networking section instead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您误解了可以使用 WinSock 发送的内容。是的 send() 被定义为一个 char* 缓冲区,但实际上它只需要一个数据缓冲区。如果今天定义了 send(),则 buf 将被定义为 void*。但我相信当 send() 被定义时, void* 并不是 C 标准的一部分。
简而言之,send() 并不考虑传递给它的指针类型,它只是获取指针指向的原始字节并将它们填充到数据包中。它从不看他们。因此,仅传递数组并没有什么问题:
然后,您必须在 send 上编写一个循环来获取数组的长度,分配该大小的数组,并在收集数组时在 receive() 上循环。
只要您的客户端和服务器都具有相同的字节顺序,您就不需要进行任何额外的处理,因为两台机器具有相同的数据格式。由于您的问题被标记为 Windows,我认为情况就是如此。
You're misunderstanding what you can send using WinSock. Yes send() is defined as taking a char* buffer, but in reality it just takes a buffer of data. If send() were defined today buf would be defined as a void*. But I believe that void* wasn't part of the C standard when sent() was defined.
The summary of that is send() doesn't case what kind of pointer you pass to it, it just takes the raw bytes the pointer points to and stuffs them into the packet. It never looks at them. So there is nothing wrong just passing the array:
Then you'll have to write a loop on send that gets the length of the array, allocates an array of that size and loops on recv() while it collects the array.
As long as both your client and server both have the same endianess, you don't need to do any extra processing since both machines have the same data format. Since you question is tagged Windows I assume that is the case.