Unix Networking Programming - Program Stuck after Reading a Message from A Client
I am currently writing a simple client and server program for both Windows and Unix. At this point in time I just wanted to create a simple client and server where the server would echo back the message to the client. I have got this to work in the windows environment but am having a very strange issue for the Unix environment. It seems after the message is received the server to print this out but then seems to get stuck. It will not attempt to send the message back to the client or even print another thing after it. I have attached the endless loop that I am using for the server. I have used the same code for the windows version and it seems to work 100% so i have no idea why this does not.
Ps This is my first post so sorry If i left anything out. I am also using Cygwin to run my Unix Code if that helps.
Thanks in advance.
for(;;)
{
char buf[1024];
int cc = recv(newsockfd, buf, sizeof(buf), 0);
if (cc == 0)
{
exit(0);
}
buf[cc] = NULL;
printf("message received: %s\n", buf);
printf("This Never Prints!");
send(newsockfd, buf, cc, 0 );
memset(&buf, '\0', sizeof(开发者_高级运维buf));
}
Richard,
It's possible that the second line doesn't print because stdout
isn't flushed.
If your socket is non-blocking, perhaps the send()
isn't working because an error in the subsequent memset
corrupts the data before it's sent.
Try changing the last three statements to
printf("This should print!\n"); // Add a newline
fflush(stdout); // Flush the output for good measure
send(newsockfd, buf, cc, 0); // Unchanged
memset(buf, '\0', sizeof(buf)); // buf is already an address.
Does that change the behavior?
精彩评论