hello stackflow users,
so i want to send and receive my binary file using sockets in c and here is how i send it from server program
send(Connections[conindex], reinterpret_cast<char*>(rawData), sizeof(rawData), NULL);
and here is how my client program receives it
char raw[647680];
recv(Connection, raw, sizeof(raw), NULL);
is there any proper way than this? i want so that i don't have to hard code the size every time. or any other alternatives etc
CodePudding user response:
A rather general way to achieve this (in both C and C ) is something like this:
if (FILE *fp = fopen(filename, "rb"))
{
size_t readBytes;
char buffer[4096];
while ((readBytes = fread(buffer, 1, sizeof(buffer), fp) > 0)
{
if (send(Connections[conindex], buffer, readBytes, 0) != readBytes)
{
handleErrors();
break;
}
}
close(Connections[conindex]);
}
And on the client side:
if (FILE *fp = fopen(filename, "wb"))
{
size_t readBytes;
char buffer[4096];
while ((readBytes = recv(socket, buffer, sizeof(buffer), 0) > 0)
{
if (fwrite(buffer, 1, readBytes, fp) != readBytes)
{
handleErrors();
break;
}
}
}
Alternatives to this rather FTP-esque connection style includes sending the size of the file first, so the client will know when to stop listening instead of waiting for the disconnect.
Please note that this code is untested and merely meant to illustrate the concept.
