Not sure what you're using for a tutorial, but Beej's guide (
link) is one of the best (the best?) out there, IMO. You should also be checking the return value of every socket-related call and reacting accordingly if it fails (e.g. perror, cleanup and exit). Read the docs for each function to find out about return values and error codes.
If you want to read more than one chunk of data, you should put your read code in a loop. Also note that each call to recv may return less than the desired number of bytes, so if you're expecting 60 bytes in a packet, something like:
Code:
len = recv(mysocket, buffer, 60, 0)
May only return 30 bytes, indicating you need to keep reading until you get a whole packet of sensor data.
Since you appear to be working with blocking sockets, I recommend a read_n_bytes function that guarantees it reads n bytes or returns with an error, i.e. it wont return with a partial packet. A rough outline goes like this:
Code:
int read_n_bytes(int socket, int flags, char *buffer, int num_bytes)
{
int bytes_read; // bytes read in one call to recv
do {
bytes_read = recv(socket, buffer, num_bytes, 0);
if (bytes_read > 0) {
// successful read
num_bytes -= bytes_read; // reduce the number of bytes left to read
buffer += bytes_read; // increment pointer to where we write data we read
}
else if (bytes_read < 0) {
// read the docs, EINTR is not a regular error, you should just call recv again with the same params
if (errno == EINTR) {
// fake out our loop condition so we try again
bytes_read = 1;
}
}
} while (bytes_read > 0 and num_bytes > 0);
return xxxx; // return some appropriate value, either total bytes read or 0 for succes, or -1 for error, or whatever works for your needs
}
Note, that is totally untested and probably not the best implementation, but should give you an idea. Then you would use it like so:
Code:
if (read_n_bytes(mysocket, header_info, HEADER_INFO_SIZE, 0) == HEADER_INFO_SIZE) {
// successful read, read sensor data in a similar manner
}