(E-Mail Removed) wrote:
> Hi,
> I'm kind of new for networking programming and need to write some
> basic socket connection (in C) using 2 linux machines that do the
> following:
> The client sends request (query) to the server, then the server needs
> to send the query results to the client. So I established the
> connection, and the client seems to get the query correctly and send
> the results back to the client. The only problem is that the client is
> either getting part of the data- when I'm using:
> /*********************************************
> RECEIVES THE OUTPUT FROM THE SERVER
> **********************************************/
> strcpy(buf, "");
> if ((numbytes=recv(sockfd, buf, MAX-1, 0)) == -1) {
> error("recv");
> exit(1);
> }
> buf[numbytes] = '\0';
> printf("%s",buf);
>
> or when I'm trying to use a while loop it got stuck forever...:
>
> /*********************************************
> RECEIVES THE OUTPUT FROM THE SERVER - loop
> **********************************************/
> strcpy(buf, "");
> while(recv(sockfd, buf, MAX-1, 0) >0) {
> printf("%s",buf);
> }
>
>
> as for the server, I'm using:
> /**********************************
> SENDS THE OUPUT
> ***********************************/
> if (send(new_fd, rdata1, MAX, 0) == -1){
> //error
> }
> close(new_fd);
> exit(0);
>
> what is wrong with this? How can I terminate the recv() in such a way
> that it should stop after getting all the data back? Any help will be
> appreciated.
>
> Thanks.
>
Well, it looks like you signify the end of the server response by
closing the connection, so this is what you should look for in
your client - keep reading from the socket until recv() returns
-1, at which point the connection is closed and you have all of
the response.
I'm rusty at C, but something like:
while (true) {
strcpy(buf, "");
numbytes=recv(sockfd, buf, MAX-1, 0)
if (numbytes == -1) {
break;
}
buf[numbytes] = '\0';
printf("%s", buf)
}
Don't use printf if your response might contain binary data
(including NULLs).
You might consider changing the server to send some kind of
end-of-message marker that you can look for instead if you are
sending text, for example, a blank line.
Steve