GetQueuedCompletionStatus blocks forever

2.3k views Asked by At

I'm writing a server application and I want to use IOCompletion ports, so I wrote a prototype for the server, but I'm facing a problem with GetQueuedCompletionStatus that it never returns(it blocks). Below is my code:

bool CreateSocketOverlappedServer()
{
  WSADATA wsaData;
  SOCKADDR_IN sockaddr;

  if(WSAStartup(MAKEWORD(2,2,),&wsaData)){
    _tprintf(_T("Unable to start up\n"));
    return false;
  }

  SrvSocket = WSASocket(AF_INET,SOCK_STREAM,0,NULL,NULL,WSA_FLAG_OVERLAPPED);
  if(SrvSocket==INVALID_SOCKET){
    _tprintf(_T("Unable to start socket\n"));
    return false;
  }

  sockaddr.sin_family = AF_INET;
  sockaddr.sin_port = htons(10000);
  sockaddr.sin_addr.s_addr = INADDR_ANY;

  /* now bind the socket */
  if(bind(SrvSocket, (SOCKADDR *)&sockaddr, sizeof(SOCKADDR_IN))==SOCKET_ERROR){
    _tprintf(_T("Unable to bind socket\n"));
    return false;
  }

  if(listen(SrvSocket, 5)==SOCKET_ERROR){
    _tprintf(_T("Error listening\n"));
    return false;
  }

  return true;
}

void WorkerThread(void *arg)
{
   bool bret= false;
   DWORD dwTransferedBytes=0;
   CLIENTS *client;
   PPER_IO_OPERATION_DATA data;

   /* Just sleep for now */
   while(true){
     _tprintf(_T("Entering while\n"));
     bret = GetQueuedCompletionStatus(hIocp,&dwTransferedBytes,(PULONG_PTR)&client,(LPOVERLAPPED *) &data,INFINITE);
     if(!bret){
       _tprintf(_T("Unable to process completion port\n"));
     }
   }
   //Sleep(10000); 
}

void AcceptClientConnections(void *arg)
{
  SOCKET ClientSocket;
  CLIENTS *c;

  _tprintf(_T("Start accepting client connections\n"));


  while(true){  
    ClientSocket = accept(SrvSocket, NULL,NULL);

    if(ClientSocket==INVALID_SOCKET){
      _tprintf(_T("Unable to accept connection\n"));
      continue;
    }

    /* do an association with completion port */
    c = (CLIENTS *)malloc(sizeof(CLIENTS));
    c->sock = ClientSocket;

    /* associate with completion port */
    if(!CreateIoCompletionPort((HANDLE)ClientSocket, hIocp,  (ULONG_PTR)c,0)){
      _tprintf(_T("Unable to associate with completion port\n: %d"),GetLastError());

    }

  }
}

Any idea? thanks in advance.

2

There are 2 answers

8
Remy Lebeau On

You are not using the Completion Port correctly, so it has nothing to do, and thus no status to report. Using a Completion Port with sockets is a two-step process, but you are only doing half of the steps.

Read the following MSDN article for details:

Windows Sockets 2.0: Write Scalable Winsock Apps Using Completion Ports

0
DriveByDeveloper On

ONe possibility: Check if you have associated the listener socket with the completion port (made this mistake myself). If you haven't the GetQueuedCompletionStatus() will block forever.