views:

67

answers:

1

Hi,

In C++ how can you use threads to not block my receive functionality in case of Sockets?

// Receive until the peer closes the connection
do {

    iResult = recv(lhSocket, recvbuf, recvbuflen, 0);
    if ( iResult > 0 )
        printf("Bytes received: %d\n", iResult);
    else if ( iResult == 0 )
        printf("Connection closed\n");
    else
        printf("recv failed: %d\n", WSAGetLastError());

} while( iResult > 0 );

closesocket(lhSocket);
WSACleanup();
+2  A: 

Call CreateThread() to create a new thread. If you want to update your UI with information received from the socket, you should define a user message for your window (with a value greater than WM_USER), and call PostMessage() to notify your window of the desired information.

Andy
@Andy : DWORD WINAPI ThreadFunc( LPVOID lpParam ){char szMsg[80];printf(szMsg, "ThreadFunc: Parameter = %d\n", ((int*)lpParam ));return 0;}void main(){DWORD dwThreadId, dwThrdParam = 1;HANDLE hThread;hThread = CreateThread(NULL, // no security attributes0, // use default stack sizeThreadFunc, // thread function // returns the thread identifier// Check the return value for success.if (hThread == NULL)CloseHandle( hThread );}is not printing anything on screen ?
Swapnil Gupta
@Swapnil It's probably because as soon as the thread is created, your program is exiting. CreateThread() will return as soon as the thread is created, so there probably isn't time for the thread to print anything. If you add a call to WaitForSingleObject() on the thread handle after the call to CreateThread(), you should see something printed.
Andy