Code:
if(recv((SOCKET)sock, NULL, 0, 0) > -1)
Seams you aren't asking to receive any data.
Here is a quick working example. It complies in MSVC as a console program but the socket and thread code would work just the same in a WIN32 GUI app.
Code:
#include <stdio.h>
#include <windows.h>
#include <winsock.h>
DWORD WINAPI Thread(LPVOID);
int main()
{
SOCKET listenSock;
WSADATA WSAData;
if (WSAStartup(MAKEWORD(1,1), &WSAData))
{
printf("WSAStartup Error %d", WSAGetLastError());
return 0;
}
listenSock=socket(AF_INET, SOCK_STREAM, 0);
if (listenSock==INVALID_SOCKET)
{ printf("Error creating socket\n");
return 0;
}
SOCKADDR_IN LocalAddress;
LocalAddress.sin_port=htons(80);
LocalAddress.sin_family=AF_INET;
LocalAddress.sin_addr.s_addr = INADDR_ANY;
if (bind(listenSock, (SOCKADDR *)&LocalAddress, sizeof(LocalAddress)))
{
printf("bind() error %d\n", WSAGetLastError());
return 0;
}
listen(listenSock, 2);
while (TRUE)
{
SOCKET tempSock = accept(listenSock, NULL, 0);
if(tempSock!=INVALID_SOCKET)
{
DWORD dwThreadID;
HANDLE hThread = CreateThread(NULL, 0, Thread, (LPVOID)tempSock, 0, &dwThreadID);
CloseHandle(hThread);
}
}
return 0;
}
DWORD WINAPI Thread(LPVOID sock)
{
char DataBuffer[1024];
while(true)
{
int nRet;
nRet=recv((SOCKET)sock, DataBuffer, 1023, 0);
if (nRet!=0 && nRet!=SOCKET_ERROR)
{ DataBuffer[nRet]=0;//Null terminate
printf("Recv->%s\n", DataBuffer);
}
else
{ shutdown((SOCKET)sock, 2);
closesocket((SOCKET)sock);
return 0;
}
}
}
Remember that recv() dosen't always return the same amount of data as the buffer size so if you know you want a certain amount of data then you need to loop.