For homework, I have to create a client/server program to store data. The client reads a file and sends it to the server via socket, the server receives it and stores the data. The final goal is to implement sharding between several servers. The program works well but the read function always read less data than I asked for when the client and server are not in the same machine
Here is my code for reading:
static inline size_t reliableRead(const int sourceSocket, void* data, const size_t nBytes)
{
size_t dataRead = 0;
unsigned int lossInARaw = 0;
do
{ const size_t readStatus = read(sourceSocket,data+dataRead,nBytes - dataRead);
if (readStatus == (unsigned)-1)
{
LOG_ERRNO_ERROR("error on read");
break;
}
dataRead += readStatus;
if (readStatus != nBytes)
LOG_WARNING("data loss(%u): read %zu/%zuo",++lossInARaw,dataRead,nBytes);
} while (dataRead < nBytes);
return dataRead;
}
Here is the result when I try to read blocks of 1024o then 8192o. First client and server are two differrents hosts, then on the same
server-side when receiving data sliced in blocks of 1024o from the client on another machine
server-side when receiving data sliced in blocks of 8192o from the client on another machine
server-side when receiving data when the client is also on the machine
From the image, read is clearly capable of reading more than 1024o. I have never socket programming before, so maybe I am missing something, how can I make the read function reads mor often the amount of data I asked it to read ? Because even without displaying the warning, this clearly increases the sending time (don't mind the timing messag, it is clearly off, I will work on that)
read
returns a value of typessize_t
, which is a signed size type. Also note thatread
will return0
when the other end of a connection have closed its socket or pipe, or you have reached end of file. Something I recommend that you handle gracefully, before it turns into an error.read
to receive all data sent by the peer. And actually, a single call toread
might actually give you more than a single "message", and that there can be a partial "message" at the end of the data you just received.ssize_t
and maybe cast tosize_t
iff there was no error (i.e., if the value was nonnegative). Using your approach, you need to compare with(size_t)-1
not(unsigned)-1
.(unsigned)-1
is usually0xffffffff
(32 bits on 64 bit platforms) but(size_t)-1
would be0xffffffffffffffff
on a 64 bit platform.