Ness
June 19th, 2004, 01:04 PM
I have a server application that obviously uses winsock. When I start this thread, all I get is junk:
DWORD WINAPI recvThread()
{
int bytes;
char *buffer = new char[256];
do
{
bytes = recv(serverTCP,buffer,256,0);
if(bytes != 0)
{
printf("Revieved a message! %c",(char *)buffer);
}
} while(true);
}
What is wrong here?
j0nas
June 19th, 2004, 01:22 PM
Originally posted by Ness
I have a server application that obviously uses winsock. When I start this thread, all I get is junk:
DWORD WINAPI recvThread()
{
int bytes;
char *buffer = new char[256];
do
{
bytes = recv(serverTCP,buffer,256,0);
if(bytes != 0)
{
printf("Revieved a message! %c",(char *)buffer);
}
} while(true);
}
What is wrong here?
I see several errors in your code:
1. No loop termination (even when recv() would return SOCKET_ERROR or 0)
2. print() statement prints out the address of buffer, as a character!
Here is corrected version for you: DWORD WINAPI recvThread()
{
int bytes;
char buffer[256]; // no need for buffer to be on heap
while ((bytes = recv(serverTCP, buffer, sizeof buffer, 0)) > 0) {
// Do something with buffer
// NOTE: If the other end is sending zero-terminated strings,
// don't expect recv() to return a complete buffer, ie. a C-string
}
if (bytes == 0) {
// Got graceful close
// Maybe shutdown the socket
// shutdown(serverTCP, SD_BOTH);
} else {
// Got a socket error, let's find out what it was
DWORD socketErr = WSAGetLastError();
printf("recv() failed with error %lu\n", socketErr);
}
closesocket(serverTCP);
}
Andreas Masur
June 20th, 2004, 08:11 AM
[Moved thread]
Mathew Joy
June 21st, 2004, 01:20 AM
If you get junk data esp only once in a while, the probable reason might be that you are assuming that you get the whole data in one recv(). The following faq (http://www.codeguru.com/forum/showthread.php?s=&threadid=296198) explains it. :cool: