Search code examples
cwindowssocketsserveriocp

Using IOCP with multiple listeners


How do I setup IOCP sockets for multiple listeners (on different ports)? Every example I find online is just a single server - multiple clients example, and I don't understand if I supposed to create multiple IOCPs, or use only one for all listeners somehow?

For example, I've found this example on GitHub, which seems to be a slight modification of some code from Win 7 SDK, and this code creates a single completion port for a single listener socket:

g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);

for( DWORD dwCPU = 0; dwCPU < g_dwThreadCount; dwCPU++ )
{
    ...
    // associate worker thread with this iocp
    hThread = CreateThread(NULL, 0, WorkerThread, g_hIOCP, 0, &dwThreadId);
    ...
}

How do I use this same thread pool for multiple completion ports? Or do I somehow only need one completion port for all listeners sockets?


Solution

  • you need only one completion port for all listeners sockets. and several threads (thread pool) which will be listen on this completion port. also possible not direct yourself create completion port and thread pool, but delegate this task to system (ntdll). this is can be done by using BindIoCompletionCallback or CreateThreadpoolIo

    so we have - single completion port, several working threads listening to this port (usual number of threads == number of processor cores) and multiple files(sockets) associated with this completion port via BindIoCompletionCallback or CreateThreadpoolIo or CreateIOCompletionPort (ugly logic - compare with ZwSetInformationFile(..FileCompletionInformation) which is internally used)