Question

I'm using a TCP IP socket program in Windows, in which i created a client for transmitting data to the server and the server is echoing the messages back to the client (please note the server has been verified working properly with telnet application).

But When I send a test message from client it gets received at the server side but when i tried to read the echoed message in client side using recv() function i wasn't getting the echoed message ,but what-ever i type on the server side it is displayed on the client side receiving recv() function

I followed the program from this link http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClientWS.c

Somebody have any solution?

Was it helpful?

Solution

This line is wrong:

if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)

The socket is in blocking mode, and the above line is attempting to read too much data as it nears the end of the message, so it will block if it does not receive as much as it is expecting.

Try this instead:

if ((bytesRcvd = recv(sock, echoBuffer, min(echoStringLen - totalBytesRcvd, RCVBUFSIZE), 0)) <= 0)

And then change this:

echoBuffer[bytesRcvd] = '\0';  /* Add \0 so printf knows where to stop */
printf("%s", echoBuffer);            /* Print the echo buffer */

To thus instead:

/* Specify bytes read so printf knows where to stop */
printf("%*s", bytesRcvd, echoBuffer);      /* Print the echo buffer */
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top