当通过 TCP 发送一个 int 数组时,为什么只有第一个数量是正确的? [英] When sending an array of int over TCP, why are only the first amount correct?

查看:38
本文介绍了当通过 TCP 发送一个 int 数组时,为什么只有第一个数量是正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照我之前的问题(为什么从 TCP 套接字读取整数数组时会得到奇怪的结果?),我想出了以下代码,它似乎可以工作.代码示例适用于少量数组元素,但一旦变大,数据就会损坏.

Following my previous question (Why do I get weird results when reading an array of integers from a TCP socket?), I have come up with the following code, which seems to work, sort of. The code sample works well with a small number of array elements, but once it becomes large, the data is corrupt toward the end.

这是通过 TCP 发送 int 数组的代码:

This is the code to send the array of int over TCP:

#define ARRAY_LEN 262144

long *sourceArrayPointer = getSourceArray();

long sourceArray[ARRAY_LEN];
for (int i = 0; i < ARRAY_LEN; i++)
{
    sourceArray[i] = sourceArrayPointer[i];
}

int result = send(clientSocketFD, sourceArray, sizeof(long) * ARRAY_LEN);

这是接收int数组的代码:

And this is the code to receive the array of int:

#define ARRAY_LEN 262144

long targetArray[ARRAY_LEN];
int result = read(socketFD, targetArray, sizeof(long) * ARRAY_LEN);

前几个数字很好,但在数组的更深处,数字开始完全不同.最后,数字应该是这样的:

The first few numbers are fine, but further down the array the numbers start going completely different. At the end, when the numbers should look like this:

0
0
0
0
0
0
0
0
0
0

但他们真的是这样出来的吗?

But they actually come out as this?

4310701
0
-12288
32767
-1
-1
10
0
-12288
32767

这是因为我使用了错误的发送/接收尺寸吗?

Is this because I'm using the wrong send/recieve size?

推荐答案

read(..., len) 的调用不会从套接字,它最多读取 len 个字节.您的数组相当大,它将被分成许多 TCP/IP 数据包,因此您对 read 的调用可能只返回数组的一部分,而其余部分仍在传输中".read() 返回它收到的字节数,所以你应该再次调用它,直到你收到你想要的一切.你可以这样做:

The call to read(..., len) doesn't read len bytes from the socket, it reads a maximum of len bytes. Your array is rather big and it will be split over many TCP/IP packets, so your call to read probably returns just a part of the array while the rest is still "in transit". read() returns how many bytes it received, so you should call it again until you received everything you want. You could do something like this:

long targetArray[ARRAY_LEN];

char *buffer = (char*)targetArray;
size_t remaining = sizeof(long) * ARRAY_LEN;
while (remaining) {
  ssize_t recvd = read(socketFD, buffer, remaining);
  // TODO: check for read errors etc here...
  remaining -= recvd;
  buffer += recvd;
}

这篇关于当通过 TCP 发送一个 int 数组时,为什么只有第一个数量是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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