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.
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);
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?
The call to
read(..., len)doesn’t readlenbytes from the socket, it reads a maximum oflenbytes. 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: