samedi 28 février 2015

C socket read() return value

I'm working on a C project to send a file from one IP address to another, using a server/client structure. From reading other posts, I understand that reading from a socket will return 0 only if the socket is closed.


Relevant code on server side (socket(), bind(), and accept() behave as expected)



char *toSend = malloc(packet_size);
size_t bytesRead;
while ((bytesRead = fread(toSend, sizeof(char), packet_size, fp)) > 0) {
printf("Sending: %s \n", toSend);
write(newsockfd, toSend);
usleep(packet_delay*1000000);
}


On client side:



char buffer[256];
int numRead;
while ((numRead = read(sockfd, buffer, 255)) > 0) {
printf("read %d\n", numRead);
printf("%s\n", buffer);
fwrite(buffer, sizeof(char), 255, fp);
}


The client connect() call returns 0 for success, but the first call to read(sockfd, buffer, 255) returns 0, despite the socket being open at the time; this seems like it shouldn't be possible. Does anyone have some tips? Thank you.


Aucun commentaire:

Enregistrer un commentaire