I am having a slight problem with transmitting data over (TCP) sockets. A little background about what I'm doing:
I am sending data from side A to B. The transmitted data may be of variable length, assuming that the maximum size should be 1096 bytes.
A) send(clientFd, buffer, size, NULL)
to B, since I don’t know what size to expect, I always try to get 1096 bytes:
B) int receivedBytes = receive(fd, msgBuff, 1096, NULL)
However, when I did this: I realized that A sends small pieces of data for about 80-90 bytes. After several outbursts of sending, B combined them together to get Bytes to be 1096. This obviously misrepresented data and hell broke.
To fix this, I broke my data into two parts: header and data.
struct IpcMsg { long msgType; int devId; uint32_t senderId; uint16_t size; uint8_t value[IPC_VALUES_SIZE]; };
On the side:
A) send(clientFd, buffer, size, NULL)
on B, I first get the header and determine the size of the payload to receive: and then I get the rest of the payload.
B) int receivedBytes = receive(fd, msgBuff, sizeof(IpcMsg) - sizeof( ((IpcMsg*)0)->value ), 0); int sizeToPoll = ((IpcMsg*)buffer)->size; printf("Size to poll: %d\n", sizeToPoll); if (sizeToPoll != 0) { bytesRead = recv(clientFd, buffer + receivedBytes, sizeToPoll, 0); }
So, for every dispatch that has a payload, I get a call twice. This worked for me, but I was wondering if there is a better way to do this?