I have a requirement to send commands and read responses from a device using IrDA sockets communication. Although packaging up the commands is fairly straight forward, determining the expected size of the response is not possible. For example the command "GET_ERRORS" results in the device returning data from 0 to n, \n
delimited lines of up to 80 bytes each. I have read the post *here, but the ***header preceding the actual data block* is not provided to me by the device.
[EDIT]
Here is a typical response from the GET_ERRORS command (shorted for readability):
Date Time Fault
10/12/2000 02:00:00 3f46
10/12/2000 02:00:00 bcf5
10/12/2000 02:00:00 1312
10/12/2000 02:00:00 a334
10/12/2000 02:00:00 b212
10/12/2000 02:00:00 b212
10/12/2000 02:00:00 c43a
%
This example, (from a SO post HERE) works well if I know the length of data being returned:
int recv_all(int sockfd, void *buf, size_t len, int flags)
{
size_t toread = len;
char *bufptr = (char*) buf;
while (toread > 0)
{
ssize_t rsz = recv(sockfd, bufptr, toread, flags);
if (rsz <= 0)
return rsz; /* Error or other end closed cnnection */
toread -= rsz; /* Read less next time */
bufptr += rsz; /* Next buffer position to read into */
}
return len;
}
But if I want to receive an unknown amount of data, the only thing I know to do is to declare a large buffer, then pass it to something like this:
int IrdaCommReceive(int irdaCommSocket, void* largeBuf, size_t len, int* rcvd)
{
char *bufptr = (char *)largeBuf;
int bytesRcvd = recv(irdaCommSocket, bufptr, len, 0);
if (bytesRcvd < 0) return WSAGetLastError();
*rcvd = bytesRcvd;
return 0;
}
Is there a better way to write a receive function for sockets data of an indeterminate size?