Click here to Skip to main content
12,628,925 members (30,310 online)
Click here to Skip to main content
Add your own
alternative version


132 bookmarked

IOCPNet - Ultimate IOCP

, 17 Jan 2006
Rate this:
Please Sign up or sign in to vote.
Easy to use, high performance, large data transfer by using IO Completion Port.


There are many articles on IOCP (Input/Output Completion Port). But they are not easy to understand because the IOCP technique itself has some arcane things and it doesn't have related standard documents which have enough explanation or code samples. So, I decided to make an IOCP sample (OIOCPNet) in high performance and write a document that deals with the way IOCP operates and its related key issues.


I focused on:

  1. More than 65,000 concurrent connections (the maximum port number (unsigned short(65535)) of IP version 4).
  2. Function to transfer more than thousand bytes through the network.
  3. Easy method for users of the OIOCPNet class.

Key ideas to achieve the objectives


Yeah, the first thing is IOCP. Well, why should we use IOCP? If we use the well known select function (with FD_SET, FD_ZERO, ...), we can't help looping to detect socket events which means that the socket has some received or sent data packets. And when we develop a game server or a chat server, a socket is used as an ID of the user action. So to find the user data on the server, we use a finding loop or hash tables with the socket number. Loops are very serious in making the server slow when the number of users is more than tens of thousands. But with IOCP, we need not do these loops. Because IOCP detects socket events at the kernel level and IOCP provides the mechanism to associate a socket (i.e. completion port) with a user data pointer directly. In short, with IOCP we can avoid loops and get the user data on the server side faster.


By using Accept (or WSAAccept) we get WSAENOBUFS (10055) error, when the number of (almost) concurrent connections is more than 30,000 (it depends on the system resource). The reason for the error is that the system can't catch up with preparing the system resource for a socket structure as fast as connections are made. So we should find a way to make socket resources before we use them, and AcceptEx is the answer. The main advantage of AcceptEx is just this - preparing sockets before use! The other features of AcceptEx are pesky, and not understandable. (See MSDN Library.)

Static memory

The use of static memory (or pre-allocated memory) on server side applications is somewhat natural and crucial. When we receive or send packets, we must use static memory. In OIOCPNet, I use my own class (OPreAllocator) to get the pre-allocated memory area.

Sliced data chunk

Have you ever met with a situation where you had to sent a large data packet (more than thousand bytes) using one function call (like WriteFile, WSASend or send) and then the receiver didn't get the data packet you had sent? If you have met, then you might have met with the problem of network hardware (routers, HUBs, and so on) and buffer - MTU (Most Transfer Unit). The least MTU of network hardware is 576 bytes, so it is better that the large packet is sliced into many smaller packets less than the least MTU size. In OIOCPNet, I have defined the unit data block size as BUFFER_UNIT_SIZE (512 bytes). If you need a bigger one, you can change it.

Don't spawn many threads

If your server logic has some kind of IO operations, it may be better to spawn many threads. Because threading is meaningful only if the environment has IO operations. But don't forget 'the more threads, the more efforts of CPU for thread scheduling'. If there are more than 10,000 threads and they are running, the operating system and the processes can't hold their normal running state, because CPU pumps all its capability into finding which thread runs next time - scheduling or context switching. For reference, OIOCPNet has two (experimental value) threads per CPU and doesn't spawn any more.

OIOCPNet - the Key

OIOCPNet is the class applied with the above ideas. The operation steps of OIOCPNet are the following:

  1. OIOCPNet prepares its resources like pre-allocated memory area, completion port, other handles and so on.
  2. OIOCPNet makes a listening socket.
  3. OIOCPNet pre-generates sockets (65,000, but I defined it as 30,000 in IOCPNet.h for OS not Win 2003, change MAX_ACCEPTABLE_SOCKET_NUM depending on your needs) and its own buffered sockets, and then puts them into acceptable mode by using AcceptEx.
  4. When a user tries to connect to the server, OIOCPNet accepts it.
  5. When a socket reads data packets, OIOCPNet puts them into its pre-allocated reading slots and then puts an event for use of the server logic.
  6. When the sever logic writes data packets, OIOCPNet puts them into its pre-allocated writing blocks and then calls PostQueuedCompletionStatus so that a worker thread sends the data packets.
  7. When a user closes the connection, OIOCPNet closes the socket but it doesn't release the memory of the buffered socket, just re-assigns it.

The following picture shows the entire mechanism of OIOCPNet. It is very simple:

Key points when writing the code


GetQueuedCompletionStatus and PostQueuedCompletionStatus lack the parameter to present the result of the IO operation. Besides the default parameters of GetQueuedCompletionStatus (or PostQueuedCompletionStatus), OIOCPNet needs more parameters for classifying the type of IO operation and a little additional information. So I used the LPOVERLAPPED parameter of GetQueuedCompletionStatus and PostQueuedCompletionStatus as my custom parameter like the thread parameter (LPVOID lpParameter, the fourth parameter) of CreateThread. OVERLAPPEDExt is the extended type of OVERLAPPED structure and it has more information. See the definition code below:

  int IOType;
  OBufferedSocket *pBuffSock;
  OTemporaryWriteData *pTempWriteData;

Life time of a variable used by an asynchronous function

In OIOCPNet, WSASend and WSARecv operate in an asynchronous way. So take care of the life time of the variables passed to the asynchronous functions.

// pTempWriteData will be freed when send IO ends.
pTempWriteData = (OTemporaryWriteData *)
m_SMMTempWriteData.Allocate(sizeof (OTemporaryWriteData));


// the size of pData 
// (the second parameter of GetBlockNeedsExternalLock)
// does not be over BUFFER_UNIT_SIZE.
  (&pBuffSockToWrite, pTempWriteData->Data, 
  &ReadSizeToWrite, &DoesItHaveMoreSequence);


  ResSend = WSASend(pTempWriteData->Socket, 
    &pTempWriteData->DataBuf, 1, 
    &WrittenSizeUseless, Flag, 
    (LPOVERLAPPED)&pTempWriteData->OLExt, 0);

In the above code snippet, pTempWriteData is allocated for being used by WSASend. WSASend returns immediately, but pTempWriteData must be alive until the real sending operation of WSASend at the OS level is over. When the sending operation is over, then release pTempWriteData like this:

if (0 != pOVL)
    ((OVERLAPPEDExt *)pOVL)->IOType 
    || IO_TYPE_WRITE == 
    ((OVERLAPPEDExt *)pOVL)->IOType))
    if (0 != ((OVERLAPPEDExt *)pOVL)->pTempWriteData)
        ((OVERLAPPEDExt *)pOVL)->pTempWriteData);

The uniqueness of socket

A normal SOCKET number itself is unique. But the OS assigns the socket number arbitrarily, the latest closed socket number could be re-assigned to a new socket connected right next to it. So it could be that:

  1. A socket is assigned with a socket number 3947 (as an example) for new connection.
  2. The server logic reads data packets using the socket.
  3. The socket is closed suddenly for user closing while the server logic doesn't know about that fact.
  4. A different socket is assigned with the same socket number 3947, (the resurrection of that socket number).
  5. The server logic writes data packets to the socket, the server meets with no problem to do so. But the data packets might be sent to a different user as a result.

To prevent this troublesome situation, OIOCPNet manages its own socket number SocketUnique, a member of OBufferedSocket.

How to use OIOCPNet


The usage of OIOCPNet is simple. See the following code snippet:

int _tmain(int argc, _TCHAR* argv[])

  WSAStartup(MAKEWORD(2,2), &WSAData);

  pIOCPNet = new OIOCPNet(&EL);
  hThread = CreateThread(0, 0, LogicThread, 
    pIOCPNet, 0, 0);

  InterlockedExchange((long *)&g_dRunning, 0);
  WaitForSingleObject(hThread, INFINITE);


  delete pIOCPNet;


  return 0;
} // _tmain()

DWORD WINAPI LogicThread(void *pParam)
  while (1 == InterlockedExchange((long *)&g_dRunning, 
    iRes = pIOCPNet->GetSocketEventData(WAIT_TIMEOUT_TEST,
      &EventType, &SocketUnique, &pReadData, 
      &ReadSize, &pBuffSock, &pSlot, &pCustData);
    if ...
    else if (RET_SOCKET_CLOSED == iRes)
      // release pCustData.

    // Process main logic.
    MainLogic(pIOCPNet, SocketUnique, pBuffSock, 
      pReadData, ReadSize);

  return 0;
} // LogicThread()

void MainLogic(OIOCPNet *pIOCPNet, DWORD SocketUnique,
  OBufferedSocket *pBuffSock, BYTE *pReadData, DWORD ReadSize)
  pIOCPNet->WriteData(SocketUnique, pBuffSock, 
    pReadData, ReadSize); // echo.
} // MainLogic()

We can set the IP address and port number with Start which prepares the necessary resources. In logic thread we can get the data packets with GetSocketEventData and we can send data packets with WriteData. After using the data, release pSlot has the pointer (pReadData) that indicates the data packet with ReleaseSocketEvent. Finally, when the main logic ends, call Stop to that OIOCPNet which releases its resource. That's all.

Take care of read and write at client side

OIOCPNet slices a large data packet into smaller packets. It adds 4-bytes packet length information to the original data packet. But the slicing and assembling operation is abstracted by GetSocketEventData and WriteData of OIOCPNet. So, we need not care about it. But you should use TCPWrite and TCPRead (see TCPFunc.h, TCPFunc.cpp in NetTestClient project) to communicate with OIOCPNet when you make the client side application connect to the server.


My report

I compiled OIOCPNet in .NET 1.1 environment. (also VC++ 6.0, blocking #include "stdafx.h"). And I located the server (IOCPNetTest) in Windows 2003 Enterprise Edition and located the test clients (NetTestClient) in several machines. The specification and performance result:

  • Test Server - OS: Windows 2003 Enterprise Edition
  • Test Server - CPU: Intel 2.8GHz (x 2)
  • Test Server - RAM: 2GB
  • Test Client: Windows XP (3~5 machines used, changing thread number)
  • Result: about 15% ~ 20% CPU Usage (when established TCP connection number is 65,000)

Other tips

When a client can't generate more than 5,000 (~ 2,000) connections to the server, check the registry. The checking step includes:

  1. Run regedit
  2. Open 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters'
  3. Add 'MaxUserPort' as DWORD value and set the value (maximum value is 65534 in decimal number).

If you need to increase the thread number of your test client to more than 2,0xx, revise the function stack size of the client application using compile option '/STACK:BYTE' or a parameter of CreateThread. Before you run the test server and test client, set TEST_IP and TEST_SERVER_IP with the IP address of your server. To see the connection number, use performance monitor or 'netstat -s' in command prompt.


  • August, 2005
    • IOCPNet first version.
    • Fixed a bug during the ending process.
    • Added a new demo and src, using Windows thread pool. (Because there've been some requests for the sample uses BindIoCompletionCallback.)


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

sleepyrea (new)
Chief Technology Officer
Korea (Republic of) Korea (Republic of)

You may also be interested in...

Comments and Discussions

QuestionIs this faster than UDT? Pin
Member 1054714321-Jul-15 22:48
memberMember 1054714321-Jul-15 22:48 
Questiona ~~~~memory leak~~~~ Pin
barcaFc29-Aug-14 0:43
memberbarcaFc29-Aug-14 0:43 
QuestionWSASend Has a Lock? Pin
Member 1085102228-May-14 19:00
memberMember 1085102228-May-14 19:00 
GeneralMy vote of 5 Pin
Member 891132829-Apr-13 23:08
memberMember 891132829-Apr-13 23:08 
GeneralClever Pin
José Vitor3-Sep-10 10:35
memberJosé Vitor3-Sep-10 10:35 
GeneralConnection Limit Pin
tanglebones6-Aug-10 12:33
membertanglebones6-Aug-10 12:33 
GeneralRe: Connection Limit Pin
H. Pham12-Oct-13 11:43
memberH. Pham12-Oct-13 11:43 
GeneralIOCP Server to Send to all clients Pin
Alfredo Mendiola Loyola7-May-10 20:41
memberAlfredo Mendiola Loyola7-May-10 20:41 
GeneralRe: IOCP Server to Send to all clients Pin
sleepyrea (new)10-May-10 9:10
membersleepyrea (new)10-May-10 9:10 
GeneralRe: IOCP Server to Send to all clients Pin
Alfredo Mendiola Loyola10-May-10 10:59
memberAlfredo Mendiola Loyola10-May-10 10:59 
GeneralRe: IOCP Server to Send to all clients Pin
sleepyrea (new)10-May-10 12:01
membersleepyrea (new)10-May-10 12:01 
GeneralAdd database code to store values in the server [modified] Pin
Alfredo Mendiola Loyola6-May-10 11:19
memberAlfredo Mendiola Loyola6-May-10 11:19 
GeneralRe: Add databe code to store values in the server Pin
sleepyrea (new)7-May-10 15:39
membersleepyrea (new)7-May-10 15:39 
Questiona question in OIOCPNetReadSlot::Put pDataIndex += (NET_SIZE_INFO_LEN + SizeToRead)? Pin
DengMing25-Nov-09 16:03
memberDengMing25-Nov-09 16:03 
AnswerRe: a question in OIOCPNetReadSlot::Put pDataIndex += (NET_SIZE_INFO_LEN + SizeToRead)? Pin
smart_bird29-Nov-09 0:15
membersmart_bird29-Nov-09 0:15 
Questionmay be a bug, who can tell me [modified] Pin
smart_bird22-Nov-09 5:48
membersmart_bird22-Nov-09 5:48 
Questionhow can i release pCustData Pin
91yuan24-Jul-09 0:06
member91yuan24-Jul-09 0:06 
AnswerRe: how can i release pCustData Pin
91yuan24-Jul-09 16:19
member91yuan24-Jul-09 16:19 
GeneralReference On Close Event Problem Pin
sleepyrea (new)16-Aug-07 2:31
membersleepyrea (new)16-Aug-07 2:31 
QuestionWhen do you plan to release an updated version... Pin
Ybbozman10-May-07 20:03
memberYbbozman10-May-07 20:03 
Questionnumber of threads spawned by thread pool when using BindIoCompletionCallback ?? Pin
Franco Tocan13-Apr-07 22:17
memberFranco Tocan13-Apr-07 22:17 
Questionwhen time update iocpnet ? Pin
game0073-Mar-07 13:07
membergame0073-Mar-07 13:07 
Generali like iocpnet .i wait for new version iocpnet class. [modified] Pin
game0073-Feb-07 22:12
membergame0073-Feb-07 22:12 
GeneralI've fixed some bugs and added new functions, but wait for ... [modified] Pin
sleepyrea (new)25-Dec-06 20:38
membersleepyrea (new)25-Dec-06 20:38 
Questionhow to get client socket close event? Pin
game00715-Dec-06 3:17
membergame00715-Dec-06 3:17 
GeneralBug report. Pin
kingsimba051115-Sep-06 0:37
memberkingsimba051115-Sep-06 0:37 
GeneralProblem in copying GBs files remotely Pin
DeveloperXone19-Jul-06 23:54
memberDeveloperXone19-Jul-06 23:54 
Questionstructured packet base communication? Pin
Hsj7-Jun-06 5:35
memberHsj7-Jun-06 5:35 
Generalmemory usage grows in task manager Pin
Hsj7-Jun-06 3:11
memberHsj7-Jun-06 3:11 
GeneralRe: memory usage grows in task manager Pin
Wjhuang8-Mar-07 5:05
memberWjhuang8-Mar-07 5:05 
Questionupdated??? please give a update comments?? Pin
xiudo7-Nov-05 16:26
memberxiudo7-Nov-05 16:26 
Answerand can you give a function to send data to all the online client??? Pin
xiudo7-Nov-05 16:33
memberxiudo7-Nov-05 16:33 
QuestioniRes = TCPRead(Sockets[Index], 0, 0, READ_TIMEOUT_TEST, &ErrorCode);??? Pin
xiudo6-Nov-05 4:08
memberxiudo6-Nov-05 4:08 
AnswerRe: iRes = TCPRead(Sockets[Index], 0, 0, READ_TIMEOUT_TEST, &ErrorCode);??? Pin
xiudo7-Nov-05 5:54
memberxiudo7-Nov-05 5:54 
QuestionFixup the OIOCPNet::m_ActiveConnectionNum will less than zero???? Pin
xiudo5-Nov-05 6:47
memberxiudo5-Nov-05 6:47 
Generalgreat job,need to make progress Pin
tiger9992-Nov-05 22:10
membertiger9992-Nov-05 22:10 
GeneralRe: great job,need to make progress Pin
xiudo3-Nov-05 23:04
memberxiudo3-Nov-05 23:04 
GeneralYou probably don't want to do it like this... Pin
Len Holgate29-Oct-05 5:25
memberLen Holgate29-Oct-05 5:25 
GeneralRe: You probably don't want to do it like this... Pin
sleepyrea (new)30-Oct-05 4:36
membersleepyrea (new)30-Oct-05 4:36 
GeneralRe: You probably don't want to do it like this... Pin
Len Holgate30-Oct-05 8:16
memberLen Holgate30-Oct-05 8:16 
GeneralRe: You probably don't want to do it like this... Pin
tiger99931-Oct-05 19:50
membertiger99931-Oct-05 19:50 
GeneralRe: You probably don't want to do it like this... Pin
sleepyrea (new)31-Oct-05 19:54
membersleepyrea (new)31-Oct-05 19:54 
GeneralRe: You probably don't want to do it like this... Pin
Len Holgate31-Oct-05 21:47
memberLen Holgate31-Oct-05 21:47 
GeneralRe: You probably don't want to do it like this... Pin
tiger9991-Nov-05 6:55
membertiger9991-Nov-05 6:55 
GeneralRe: You probably don't want to do it like this... Pin
Len Holgate1-Nov-05 7:18
memberLen Holgate1-Nov-05 7:18 
GeneralRe: You probably don't want to do it like this... Pin
tiger9991-Nov-05 16:05
membertiger9991-Nov-05 16:05 
GeneralRe: You probably don't want to do it like this... Pin
Len Holgate1-Nov-05 22:26
memberLen Holgate1-Nov-05 22:26 
GeneralRe: You probably don't want to do it like this... Pin
tiger9992-Nov-05 14:59
membertiger9992-Nov-05 14:59 
GeneralRe: You probably don't want to do it like this... Pin
Len Holgate2-Nov-05 22:17
memberLen Holgate2-Nov-05 22:17 
GeneralRe: You probably don't want to do it like this... Pin
Len Holgate3-Nov-05 12:30
memberLen Holgate3-Nov-05 12:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161205.3 | Last Updated 17 Jan 2006
Article Copyright 2005 by sleepyrea (new)
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid