سؤال

I have problems with a read() statement where I'm passing an integer from a server to the client. The problem is that I can send 2 integers to the server just fine, but for some reason the client fails to receive anything from the server except 0. Could someone explain to me what is actually going on with this while loop? It seems like a standard practice in C Sockets, but I can't figure out what (if anything) it is really accomplishing.

memset(rbuffer,0,sizeof(rbuffer));
while ( (n = read(sockfd, rbuffer, sizeof(rbuffer))) > 0)
{
    rbuffer[n] = 0;
}

This is the read attempt on the client side, where rbuffer is supposed to accept a single integer. It appears that it attempts to read over and over from the server (recieving n > 0 until the server closes the socket) where the last read before the socket closes actually holds the data, thus, rbuffer is set to 0 until completion, where it is then filled with the data from the server.

The code on the server side to send to the client appears like this:

int g = dijkstra(source, destination, numNodes);
printf("The value sent to client is %d.\n", g);
write(connfd, g, sizeof(g));

close(connfd);
  sleep(1);

and the original code appears as:

int g = dijkstra(source, destination, numNodes);
sprintf(sendBuff,"%d", g);
write(connfd, sendBuff, strlen(sendBuff)); 

close(connfd);
  sleep(1);

But I want to read it as an integer at the client side and so I cut out sendBuff as it seemed unnecessary when sending an int, considering g was already set.

I appreciate any help. What I would like is a better understanding of the server to client communication of TCP sockets in C, specifically does read need to wait for a server response, or does it do that already? Also, cutting out the while loop for the read has no effect, the response is still 0 from the server for *buffer.

هل كانت مفيدة؟

المحلول

You cannot use write(connfd, g, sizeof(g));, the write function is expecting a char pointer as second parameter, and you are giving it a int. This is without saying that your original client is probably also expecting a string, filling out rbuffer with the characters, and adding the ending zero (rbuffer[n] = 0) to be able to use it as string for extracting the integer. You probably have a sscanf() on the client side.

What you are literally trying to do is this

write(connfd, (char*)&g, sizeof(g));

And could receive it as such, after the while, g being an int

g = *((int*)rbuffer);

But I should not even propose this, as it is not proper code...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top