通过 Winsocks 发送 int 数组

发布于 2024-08-29 10:21:12 字数 244 浏览 3 评论 0原文

我正在尝试通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浴红衣 2024-09-05 10:21:12

您误解了可以使用 WinSock 发送的内容。是的 send() 被定义为一个 char* 缓冲区,但实际上它只需要一个数据缓冲区。如果今天定义了 send(),则 buf 将被定义为 void*。但我相信当 send() 被定义时, void* 并不是 C 标准的一部分。

简而言之,send() 并不考虑传递给它的指针类型,它只是获取指针指向的原始字节并将它们填充到数据包中。它从不看他们。因此,仅传递数组并没有什么问题:

int sendArray(SOCKET sock, int array[], int arrayLen) {
    // You need to send the array length so the receiver knows
    // how long the array is
    int bytesSent = send(sock, (char*)&arrayLen, sizeof(arrayLen));

    if (bytesSent != SOCKET_ERROR) {
       // If that worked, send the 
       bytesSent = send(sock, (char*)array, sizeof(array[0]) * arrayLen);
    }

    return bytesSent;
}

然后,您必须在 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:

int sendArray(SOCKET sock, int array[], int arrayLen) {
    // You need to send the array length so the receiver knows
    // how long the array is
    int bytesSent = send(sock, (char*)&arrayLen, sizeof(arrayLen));

    if (bytesSent != SOCKET_ERROR) {
       // If that worked, send the 
       bytesSent = send(sock, (char*)array, sizeof(array[0]) * arrayLen);
    }

    return bytesSent;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文