Winsock IO模型之IOCP模型 .

转自:http://blog.csdn.net/lostyears/article/details/7436802

  Windows平台上伸缩性最好的一种I/O模型莫过IOCP了,不过设计和实现起来比较复杂一些。针对成千上万个套接字的并发处理,IOCP采用了线程池+队列+重叠结构的内核机制完成任务。需要说明的是IOCP其实不仅可以接受套接字对象句柄,还可以接受文件对象句柄等。

    为避免线程上下文切换,它采用了线程池。除此之外,在基于事件模型或重叠模型中不得不遇到WSAWaitForMultipleEvent的WSA_MAXIMUM_WAIT_EVENTS的限制,由此必须由自己来设计线程池来避开这种限制。而IOCP则由系统来实现线程池,对用户来说透明,由此减少了设计线程池带来的复杂性并提高了安全性。看看GetQueuedCompletionStatus这个函数,它包含了封包队列排队机制以及基于事件的重叠结构OVERLAPPED的通知,用户无需再去设计队列和OVERLAPPED结构中显示地创建事件。

    IOCP一般被用于Windows平台上大规模服务器程序的设计。所以设计起来有很多地方需要注意。因为IOCP设计中需要用到很多异步操作,所以对到来的数据包的排序是需要额外处理的,简单和常用的方法是为每个封包添加一个序列号。接受方每接受一个封包就需要判断其是否为当前需要读取的下一个序列号封包,如果不是就要将之插入封包队列,如果是则返回给用户。当关闭IOCP时,我们要避免重叠操作正在进行的时候却要释放它的OVERLAPPED结构,阻止其发生的最好方法是在每个套接字句柄上调用closesocket,如此所有的未决重叠IO操作都会完成。一旦所有的套接字句柄关闭,就该终止IOCP上处理IO的工作线程了。这可以通过PostQueuedCompletionStatus来操作。在接受连接方面,投递多少连接是个需要认真考虑的问题,因为每创建一个套接字都会占用系统不小的开销,在Win2000及以后版本中我们可以通过在创建监听套接字时采用WSAEventSelect,注册FD_ACCEPT通知消息的方式,在投递的AcceptEx用完时但仍有客户连接时,事件对象将会受信,通知我们继续投递。另外,我们可以对每个客户套接字采用定时轮询的方法查询其连接时间长短,以此我们可以判断哪些客户连接有恶意的迹象(只连接服务器不发送任何数据)。

    采用书上的一个例子,其中增加Keeplive机制,并修订了其中的几个错误:

  1. ////////////////////////////////////////   
  2. // IOCP.h文件   
  3.   
  4. #ifndef __IOCP_H__   
  5. #define __IOCP_H__   
  6.   
  7. #include <winsock2.h>   
  8. #include <windows.h>   
  9. #include <Mswsock.h>   
  10.   
  11. #define BUFFER_SIZE 1024*4  // I/O请求的缓冲区大小   
  12. #define MAX_THREAD  2       // I/O服务线程的数量   
  13.   
  14.   
  15. // 这是per-I/O数据。它包含了在套节字上处理I/O操作的必要信息   
  16. struct CIOCPBuffer  
  17. {  
  18.     WSAOVERLAPPED ol;  
  19.   
  20.     SOCKET sClient;         // AcceptEx接收的客户方套节字   
  21.   
  22.     char *buff;             // I/O操作使用的缓冲区   
  23.     int nLen;               // buff缓冲区(使用的)大小   
  24.   
  25.     ULONG nSequenceNumber;  // 此I/O的序列号   
  26.   
  27.     int nOperation;         // 操作类型   
  28. #define OP_ACCEPT   1   
  29. #define OP_WRITE    2   
  30. #define OP_READ     3   
  31.   
  32.     CIOCPBuffer *pNext;  
  33. };  
  34.   
  35. // 这是per-Handle数据。它包含了一个套节字的信息   
  36. struct CIOCPContext  
  37. {  
  38.     SOCKET s;                       // 套节字句柄   
  39.   
  40.     SOCKADDR_IN addrLocal;          // 连接的本地地址   
  41.     SOCKADDR_IN addrRemote;         // 连接的远程地址   
  42.   
  43.     BOOL bClosing;                  // 套节字是否关闭   
  44.   
  45.     int nOutstandingRecv;           // 此套节字上抛出的重叠操作的数量   
  46.     int nOutstandingSend;  
  47.   
  48.   
  49.     ULONG nReadSequence;            // 安排给接收的下一个序列号   
  50.     ULONG nCurrentReadSequence;     // 当前要读的序列号   
  51.     CIOCPBuffer *pOutOfOrderReads;  // 记录没有按顺序完成的读I/O   
  52.   
  53.     CRITICAL_SECTION Lock;          // 保护这个结构   
  54.   
  55.     bool bNotifyCloseOrError;       // [2009.8.22 add Lostyears][当套接字关闭或出错时是否已通知过]   
  56.   
  57.     CIOCPContext *pNext;  
  58. };  
  59.   
  60.   
  61. class CIOCPServer   // 处理线程   
  62. {  
  63. public:  
  64.     CIOCPServer();  
  65.     ~CIOCPServer();  
  66.   
  67.     // 开始服务   
  68.     BOOL Start(int nPort = 4567, int nMaxConnections = 2000,   
  69.             int nMaxFreeBuffers = 200, int nMaxFreeContexts = 100, int nInitialReads = 4);   
  70.     // 停止服务   
  71.     void Shutdown();  
  72.   
  73.     // 关闭一个连接和关闭所有连接   
  74.     void CloseAConnection(CIOCPContext *pContext);  
  75.     void CloseAllConnections();   
  76.   
  77.     // 取得当前的连接数量   
  78.     ULONG GetCurrentConnection() { return m_nCurrentConnection; }  
  79.   
  80.     // 向指定客户发送文本   
  81.     BOOL SendText(CIOCPContext *pContext, char *pszText, int nLen);   
  82.   
  83. protected:  
  84.   
  85.     // 申请和释放缓冲区对象   
  86.     CIOCPBuffer *AllocateBuffer(int nLen);  
  87.     void ReleaseBuffer(CIOCPBuffer *pBuffer);  
  88.   
  89.     // 申请和释放套节字上下文   
  90.     CIOCPContext *AllocateContext(SOCKET s);  
  91.     void ReleaseContext(CIOCPContext *pContext);  
  92.   
  93.     // 释放空闲缓冲区对象列表和空闲上下文对象列表   
  94.     void FreeBuffers();  
  95.     void FreeContexts();  
  96.   
  97.     // 向连接列表中添加一个连接   
  98.     BOOL AddAConnection(CIOCPContext *pContext);  
  99.   
  100.     // 插入和移除未决的接受请求   
  101.     BOOL InsertPendingAccept(CIOCPBuffer *pBuffer);  
  102.     BOOL RemovePendingAccept(CIOCPBuffer *pBuffer);  
  103.   
  104.     // 取得下一个要读取的   
  105.     CIOCPBuffer *GetNextReadBuffer(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  106.   
  107.   
  108.     // 投递接受I/O、发送I/O、接收I/O   
  109.     BOOL PostAccept(CIOCPBuffer *pBuffer);  
  110.     BOOL PostSend(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  111.     BOOL PostRecv(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  112.   
  113.     void HandleIO(DWORD dwKey, CIOCPBuffer *pBuffer, DWORD dwTrans, int nError);  
  114.   
  115.   
  116.     // [2009.8.22 add Lostyears]   
  117.     // 当套件字关闭或出错时通知   
  118.     void NotifyConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  119.     void NotifyConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError);  
  120.   
  121.         // 事件通知函数   
  122.     // 建立了一个新的连接   
  123.     virtual void OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  124.     // 一个连接关闭   
  125.     virtual void OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  126.     // 在一个连接上发生了错误   
  127.     virtual void OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError);  
  128.     // 一个连接上的读操作完成   
  129.     virtual void OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  130.     // 一个连接上的写操作完成   
  131.     virtual void OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer);  
  132.   
  133. protected:  
  134.   
  135.     // 记录空闲结构信息   
  136.     CIOCPBuffer *m_pFreeBufferList;  
  137.     CIOCPContext *m_pFreeContextList;  
  138.     int m_nFreeBufferCount;  
  139.     int m_nFreeContextCount;      
  140.     CRITICAL_SECTION m_FreeBufferListLock;  
  141.     CRITICAL_SECTION m_FreeContextListLock;  
  142.   
  143.     // 记录抛出的Accept请求   
  144.     CIOCPBuffer *m_pPendingAccepts;   // 抛出请求列表。   
  145.     long m_nPendingAcceptCount;  
  146.     CRITICAL_SECTION m_PendingAcceptsLock;  
  147.   
  148.     // 记录连接列表   
  149.     CIOCPContext *m_pConnectionList;  
  150.     int m_nCurrentConnection;  
  151.     CRITICAL_SECTION m_ConnectionListLock;  
  152.   
  153.     // 用于投递Accept请求   
  154.     HANDLE m_hAcceptEvent;  
  155.     HANDLE m_hRepostEvent;  
  156.     LONG m_nRepostCount;  
  157.   
  158.     int m_nPort;                // 服务器监听的端口   
  159.   
  160.     int m_nInitialAccepts;      // 开始时抛出的异步接收投递数   
  161.     int m_nInitialReads;  
  162.     int m_nMaxAccepts;          // 抛出的异步接收投递数最大值   
  163.     int m_nMaxSends;            // 抛出的异步发送投递数最大值(跟踪投递的发送的数量,防止用户仅发送数据而不接收,导致服务器抛出大量发送操作)   
  164.     int m_nMaxFreeBuffers;      // 内存池中容纳的最大内存块数(超过该数将在物理上释放内存池)   
  165.     int m_nMaxFreeContexts;     // 上下文[套接字信息]内存池中容纳的最大上下文内存块数(超过该数将在物理上释放上下文内存池)   
  166.     int m_nMaxConnections;      // 最大连接数   
  167.   
  168.     HANDLE m_hListenThread;         // 监听线程   
  169.     HANDLE m_hCompletion;           // 完成端口句柄   
  170.     SOCKET m_sListen;               // 监听套节字句柄   
  171.     LPFN_ACCEPTEX m_lpfnAcceptEx;   // AcceptEx函数地址   
  172.     LPFN_GETACCEPTEXSOCKADDRS m_lpfnGetAcceptExSockaddrs; // GetAcceptExSockaddrs函数地址   
  173.   
  174.     BOOL m_bShutDown;       // 用于通知监听线程退出   
  175.     BOOL m_bServerStarted;  // 记录服务是否启动   
  176.   
  177.     CRITICAL_SECTION m_CloseOrErrLock;  // [2009.9.1 add Lostyears]   
  178.   
  179. private:    // 线程函数   
  180.     static DWORD WINAPI _ListenThreadProc(LPVOID lpParam);  
  181.     static DWORD WINAPI _WorkerThreadProc(LPVOID lpParam);  
  182. };  
  183.   
  184.   
  185. #endif // __IOCP_H__   
  186. //////////////////////////////////////////////////   
  187. // IOCP.cpp文件   
  188.   
  189. #include "iocp.h"   
  190. #pragma comment(lib, "WS2_32.lib")   
  191. #include <stdio.h>   
  192. #include <mstcpip.h>   
  193.   
  194. CIOCPServer::CIOCPServer()  
  195. {  
  196.     // 列表   
  197.     m_pFreeBufferList = NULL;  
  198.     m_pFreeContextList = NULL;    
  199.     m_pPendingAccepts = NULL;  
  200.     m_pConnectionList = NULL;  
  201.   
  202.     m_nFreeBufferCount = 0;  
  203.     m_nFreeContextCount = 0;  
  204.     m_nPendingAcceptCount = 0;  
  205.     m_nCurrentConnection = 0;  
  206.   
  207.     ::InitializeCriticalSection(&m_FreeBufferListLock);  
  208.     ::InitializeCriticalSection(&m_FreeContextListLock);  
  209.     ::InitializeCriticalSection(&m_PendingAcceptsLock);  
  210.     ::InitializeCriticalSection(&m_ConnectionListLock);  
  211.     ::InitializeCriticalSection(&m_CloseOrErrLock); // [2009.9.1 add Lostyears]   
  212.   
  213.     // Accept请求   
  214.     m_hAcceptEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);  
  215.     m_hRepostEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);  
  216.     m_nRepostCount = 0;  
  217.   
  218.     m_nPort = 4567;  
  219.   
  220.     m_nInitialAccepts = 10;  
  221.     m_nInitialReads = 4;  
  222.     m_nMaxAccepts = 100;  
  223.     m_nMaxSends = 20;  
  224.     m_nMaxFreeBuffers = 200;  
  225.     m_nMaxFreeContexts = 100;  
  226.     m_nMaxConnections = 2000;  
  227.   
  228.     m_hListenThread = NULL;  
  229.     m_hCompletion = NULL;  
  230.     m_sListen = INVALID_SOCKET;  
  231.     m_lpfnAcceptEx = NULL;  
  232.     m_lpfnGetAcceptExSockaddrs = NULL;  
  233.   
  234.     m_bShutDown = FALSE;  
  235.     m_bServerStarted = FALSE;  
  236.       
  237.     // 初始化WS2_32.dll   
  238.     WSADATA wsaData;  
  239.     WORD sockVersion = MAKEWORD(2, 2);  
  240.     ::WSAStartup(sockVersion, &wsaData);  
  241. }  
  242.   
  243. CIOCPServer::~CIOCPServer()  
  244. {  
  245.     Shutdown();  
  246.   
  247.     if(m_sListen != INVALID_SOCKET)  
  248.         ::closesocket(m_sListen);  
  249.     if(m_hListenThread != NULL)  
  250.         ::CloseHandle(m_hListenThread);  
  251.   
  252.     ::CloseHandle(m_hRepostEvent);  
  253.     ::CloseHandle(m_hAcceptEvent);  
  254.   
  255.     ::DeleteCriticalSection(&m_FreeBufferListLock);  
  256.     ::DeleteCriticalSection(&m_FreeContextListLock);  
  257.     ::DeleteCriticalSection(&m_PendingAcceptsLock);  
  258.     ::DeleteCriticalSection(&m_ConnectionListLock);  
  259.     ::DeleteCriticalSection(&m_CloseOrErrLock); // [2009.9.1 add Lostyears]   
  260.   
  261.     ::WSACleanup();   
  262. }  
  263.   
  264.   
  265. ///////////////////////////////////   
  266. // 自定义帮助函数   
  267.   
  268. CIOCPBuffer *CIOCPServer::AllocateBuffer(int nLen)  
  269. {  
  270.     CIOCPBuffer *pBuffer = NULL;  
  271.     if(nLen > BUFFER_SIZE)  
  272.         return NULL;  
  273.   
  274.     // 为缓冲区对象申请内存   
  275.     ::EnterCriticalSection(&m_FreeBufferListLock);  
  276.     if(m_pFreeBufferList == NULL)  // 内存池为空,申请新的内存   
  277.     {  
  278.         pBuffer = (CIOCPBuffer *)::HeapAlloc(GetProcessHeap(),   
  279.                         HEAP_ZERO_MEMORY, sizeof(CIOCPBuffer) + BUFFER_SIZE);  
  280.     }  
  281.     else    // 从内存池中取一块来使用   
  282.     {  
  283.         pBuffer = m_pFreeBufferList;  
  284.         m_pFreeBufferList = m_pFreeBufferList->pNext;      
  285.         pBuffer->pNext = NULL;  
  286.         m_nFreeBufferCount --;  
  287.     }  
  288.     ::LeaveCriticalSection(&m_FreeBufferListLock);  
  289.   
  290.     // 初始化新的缓冲区对象   
  291.     if(pBuffer != NULL)  
  292.     {  
  293.         pBuffer->buff = (char*)(pBuffer + 1);  
  294.         pBuffer->nLen = nLen;  
  295.         //::ZeroMemory(pBuffer->buff, pBuffer->nLen);   
  296.     }  
  297.     return pBuffer;  
  298. }  
  299.   
  300. void CIOCPServer::ReleaseBuffer(CIOCPBuffer *pBuffer)  
  301. {  
  302.     ::EnterCriticalSection(&m_FreeBufferListLock);  
  303.   
  304.     if(m_nFreeBufferCount < m_nMaxFreeBuffers)   // 将要释放的内存添加到空闲列表中 [2010.5.15 mod Lostyears]old:m_nFreeBufferCount <= m_nMaxFreeBuffers   
  305.     {  
  306.         memset(pBuffer, 0, sizeof(CIOCPBuffer) + BUFFER_SIZE);  
  307.         pBuffer->pNext = m_pFreeBufferList;  
  308.         m_pFreeBufferList = pBuffer;  
  309.   
  310.         m_nFreeBufferCount ++ ;  
  311.     }  
  312.     else            // 已经达到最大值,真正的释放内存   
  313.     {  
  314.         ::HeapFree(::GetProcessHeap(), 0, pBuffer);  
  315.     }  
  316.   
  317.     ::LeaveCriticalSection(&m_FreeBufferListLock);  
  318. }  
  319.   
  320.   
  321. CIOCPContext *CIOCPServer::AllocateContext(SOCKET s)  
  322. {  
  323.     CIOCPContext *pContext;  
  324.   
  325.     // 申请一个CIOCPContext对象   
  326.     ::EnterCriticalSection(&m_FreeContextListLock);  
  327.     if(m_pFreeContextList == NULL)  
  328.     {  
  329.         pContext = (CIOCPContext *)  
  330.                 ::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CIOCPContext));   
  331.   
  332.         ::InitializeCriticalSection(&pContext->Lock);  
  333.     }  
  334.     else      
  335.     {  
  336.         // 在空闲列表中申请   
  337.         pContext = m_pFreeContextList;  
  338.         m_pFreeContextList = m_pFreeContextList->pNext;  
  339.         pContext->pNext = NULL;  
  340.   
  341.         m_nFreeContextCount --; // [2009.8.9 mod Lostyears][old: m_nFreeBufferCount--]    
  342.     }  
  343.   
  344.     ::LeaveCriticalSection(&m_FreeContextListLock);  
  345.   
  346.     // 初始化对象成员   
  347.     if(pContext != NULL)  
  348.     {  
  349.         pContext->s = s;  
  350.   
  351.         // [2009.8.22 add Lostyears]   
  352.         pContext->bNotifyCloseOrError = false;  
  353.     }  
  354.   
  355.     return pContext;  
  356. }  
  357.   
  358. void CIOCPServer::ReleaseContext(CIOCPContext *pContext)  
  359. {  
  360.     if(pContext->s != INVALID_SOCKET)  
  361.         ::closesocket(pContext->s);  
  362.   
  363.     // 首先释放(如果有的话)此套节字上的没有按顺序完成的读I/O的缓冲区   
  364.     CIOCPBuffer *pNext;  
  365.     while(pContext->pOutOfOrderReads != NULL)  
  366.     {  
  367.         pNext = pContext->pOutOfOrderReads->pNext;  
  368.         ReleaseBuffer(pContext->pOutOfOrderReads);  
  369.         pContext->pOutOfOrderReads = pNext;  
  370.     }  
  371.   
  372.     ::EnterCriticalSection(&m_FreeContextListLock);  
  373.       
  374.     if(m_nFreeContextCount < m_nMaxFreeContexts) // 添加到空闲列表 [2010.4.10 mod Lostyears][old: m_nFreeContextCount <= m_nMaxFreeContexts]如果m_nFreeContextCount==m_nMaxFreeContexts时,会在下一次导致m_nFreeContextCount>m_nMaxFreeContexts   
  375.   
  376.     {  
  377.         // 先将关键代码段变量保存到一个临时变量中   
  378.         CRITICAL_SECTION cstmp = pContext->Lock;  
  379.   
  380.         // 将要释放的上下文对象初始化为0   
  381.         memset(pContext, 0, sizeof(CIOCPContext));  
  382.   
  383.         // 再放会关键代码段变量,将要释放的上下文对象添加到空闲列表的表头   
  384.         pContext->Lock = cstmp;  
  385.         pContext->pNext = m_pFreeContextList;  
  386.         m_pFreeContextList = pContext;  
  387.           
  388.         // 更新计数   
  389.         m_nFreeContextCount ++;  
  390.     }  
  391.     else // 已经达到最大值,真正地释放   
  392.     {  
  393.         ::DeleteCriticalSection(&pContext->Lock);  
  394.         ::HeapFree(::GetProcessHeap(), 0, pContext);  
  395.         pContext = NULL;  
  396.     }  
  397.   
  398.     ::LeaveCriticalSection(&m_FreeContextListLock);  
  399. }  
  400.   
  401. void CIOCPServer::FreeBuffers()  
  402. {  
  403.     // 遍历m_pFreeBufferList空闲列表,释放缓冲区池内存   
  404.     ::EnterCriticalSection(&m_FreeBufferListLock);  
  405.   
  406.     CIOCPBuffer *pFreeBuffer = m_pFreeBufferList;  
  407.     CIOCPBuffer *pNextBuffer;  
  408.     while(pFreeBuffer != NULL)  
  409.     {  
  410.         pNextBuffer = pFreeBuffer->pNext;  
  411.         if(!::HeapFree(::GetProcessHeap(), 0, pFreeBuffer))  
  412.         {  
  413. #ifdef _DEBUG   
  414.             ::OutputDebugString("  FreeBuffers释放内存出错!");  
  415. #endif // _DEBUG   
  416.             break;  
  417.         }  
  418.         pFreeBuffer = pNextBuffer;  
  419.     }  
  420.     m_pFreeBufferList = NULL;  
  421.     m_nFreeBufferCount = 0;  
  422.   
  423.     ::LeaveCriticalSection(&m_FreeBufferListLock);  
  424. }  
  425.   
  426. void CIOCPServer::FreeContexts()  
  427. {  
  428.     // 遍历m_pFreeContextList空闲列表,释放缓冲区池内存   
  429.     ::EnterCriticalSection(&m_FreeContextListLock);  
  430.       
  431.     CIOCPContext *pFreeContext = m_pFreeContextList;  
  432.     CIOCPContext *pNextContext;  
  433.     while(pFreeContext != NULL)  
  434.     {  
  435.         pNextContext = pFreeContext->pNext;  
  436.           
  437.         ::DeleteCriticalSection(&pFreeContext->Lock);  
  438.         if(!::HeapFree(::GetProcessHeap(), 0, pFreeContext))  
  439.         {  
  440. #ifdef _DEBUG   
  441.             ::OutputDebugString("  FreeBuffers释放内存出错!");  
  442. #endif // _DEBUG   
  443.             break;  
  444.         }  
  445.         pFreeContext = pNextContext;  
  446.     }  
  447.     m_pFreeContextList = NULL;  
  448.     m_nFreeContextCount = 0;  
  449.   
  450.     ::LeaveCriticalSection(&m_FreeContextListLock);  
  451. }  
  452.   
  453.   
  454. BOOL CIOCPServer::AddAConnection(CIOCPContext *pContext)  
  455. {  
  456.     // 向客户连接列表添加一个CIOCPContext对象   
  457.   
  458.     ::EnterCriticalSection(&m_ConnectionListLock);  
  459.     if(m_nCurrentConnection < m_nMaxConnections)  
  460.     {  
  461.         // 添加到表头   
  462.         pContext->pNext = m_pConnectionList;  
  463.         m_pConnectionList = pContext;  
  464.         // 更新计数   
  465.         m_nCurrentConnection ++;  
  466.   
  467.         ::LeaveCriticalSection(&m_ConnectionListLock);  
  468.         return TRUE;  
  469.     }  
  470.     ::LeaveCriticalSection(&m_ConnectionListLock);  
  471.   
  472.     return FALSE;  
  473. }  
  474.   
  475. void CIOCPServer::CloseAConnection(CIOCPContext *pContext)  
  476. {  
  477.     // 首先从列表中移除要关闭的连接   
  478.     ::EnterCriticalSection(&m_ConnectionListLock);  
  479.   
  480.     CIOCPContext* pTest = m_pConnectionList;  
  481.     if(pTest == pContext)  
  482.     {  
  483.         m_pConnectionList =  pTest->pNext; // [2009.8.9 mod Lostyears][old: m_pConnectionList =  pContext->pNext]   
  484.         m_nCurrentConnection --;  
  485.     }  
  486.     else  
  487.     {  
  488.         while(pTest != NULL && pTest->pNext !=  pContext)  
  489.             pTest = pTest->pNext;  
  490.         if(pTest != NULL)  
  491.         {  
  492.             pTest->pNext =  pContext->pNext;  
  493.             m_nCurrentConnection --;  
  494.         }  
  495.     }  
  496.       
  497.     ::LeaveCriticalSection(&m_ConnectionListLock);  
  498.   
  499.     // 然后关闭客户套节字   
  500.     ::EnterCriticalSection(&pContext->Lock);  
  501.   
  502.     if(pContext->s != INVALID_SOCKET)  
  503.     {  
  504.         ::closesocket(pContext->s);    
  505.         pContext->s = INVALID_SOCKET;  
  506.     }  
  507.     pContext->bClosing = TRUE;  
  508.   
  509.     ::LeaveCriticalSection(&pContext->Lock);  
  510. }  
  511.   
  512. void CIOCPServer::CloseAllConnections()  
  513. {  
  514.     // 遍历整个连接列表,关闭所有的客户套节字   
  515.   
  516.     ::EnterCriticalSection(&m_ConnectionListLock);  
  517.   
  518.     CIOCPContext *pContext = m_pConnectionList;  
  519.     while(pContext != NULL)  
  520.     {     
  521.         ::EnterCriticalSection(&pContext->Lock);  
  522.   
  523.         if(pContext->s != INVALID_SOCKET)  
  524.         {  
  525.             ::closesocket(pContext->s);  
  526.             pContext->s = INVALID_SOCKET;  
  527.         }  
  528.   
  529.         pContext->bClosing = TRUE;  
  530.   
  531.         ::LeaveCriticalSection(&pContext->Lock);   
  532.           
  533.         pContext = pContext->pNext;  
  534.     }  
  535.   
  536.     m_pConnectionList = NULL;  
  537.     m_nCurrentConnection = 0;  
  538.   
  539.     ::LeaveCriticalSection(&m_ConnectionListLock);  
  540. }  
  541.   
  542.   
  543. BOOL CIOCPServer::InsertPendingAccept(CIOCPBuffer *pBuffer)  
  544. {  
  545.     // 将一个I/O缓冲区对象插入到m_pPendingAccepts表中   
  546.   
  547.     ::EnterCriticalSection(&m_PendingAcceptsLock);  
  548.   
  549.     if(m_pPendingAccepts == NULL)  
  550.         m_pPendingAccepts = pBuffer;  
  551.     else  
  552.     {  
  553.         pBuffer->pNext = m_pPendingAccepts;  
  554.         m_pPendingAccepts = pBuffer;  
  555.     }  
  556.     m_nPendingAcceptCount ++;  
  557.   
  558.     ::LeaveCriticalSection(&m_PendingAcceptsLock);  
  559.   
  560.     return TRUE;  
  561. }  
  562.   
  563. BOOL CIOCPServer::RemovePendingAccept(CIOCPBuffer *pBuffer)  
  564. {  
  565.     BOOL bResult = FALSE;  
  566.   
  567.     // 遍历m_pPendingAccepts表,从中移除pBuffer所指向的缓冲区对象   
  568.     ::EnterCriticalSection(&m_PendingAcceptsLock);  
  569.   
  570.     CIOCPBuffer *pTest = m_pPendingAccepts;  
  571.     if(pTest == pBuffer)    // 如果是表头元素   
  572.     {  
  573.         m_pPendingAccepts = pTest->pNext; // [2009.8.9 mod Lostyears][old: m_pPendingAccepts = pBuffer->pNext]   
  574.         bResult = TRUE;  
  575.     }  
  576.     else                    // 不是表头元素的话,就要遍历这个表来查找了   
  577.     {  
  578.         while(pTest != NULL && pTest->pNext != pBuffer)  
  579.             pTest = pTest->pNext;  
  580.         if(pTest != NULL)  
  581.         {  
  582.             pTest->pNext = pBuffer->pNext;  
  583.              bResult = TRUE;  
  584.         }  
  585.     }  
  586.     // 更新计数   
  587.     if(bResult)  
  588.         m_nPendingAcceptCount --;  
  589.   
  590.     ::LeaveCriticalSection(&m_PendingAcceptsLock);  
  591.   
  592.     return  bResult;  
  593. }  
  594.   
  595.   
  596. CIOCPBuffer *CIOCPServer::GetNextReadBuffer(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  597. {  
  598.     if(pBuffer != NULL)  
  599.     {  
  600.         // 如果与要读的下一个序列号相等,则读这块缓冲区   
  601.         if(pBuffer->nSequenceNumber == pContext->nCurrentReadSequence)  
  602.         {  
  603.             return pBuffer;  
  604.         }  
  605.           
  606.         // 如果不相等,则说明没有按顺序接收数据,将这块缓冲区保存到连接的pOutOfOrderReads列表中   
  607.   
  608.         // 列表中的缓冲区是按照其序列号从小到大的顺序排列的   
  609.   
  610.         pBuffer->pNext = NULL;  
  611.           
  612.         CIOCPBuffer *ptr = pContext->pOutOfOrderReads;  
  613.         CIOCPBuffer *pPre = NULL;  
  614.         while(ptr != NULL)  
  615.         {  
  616.             if(pBuffer->nSequenceNumber < ptr->nSequenceNumber)  
  617.                 break;  
  618.               
  619.             pPre = ptr;  
  620.             ptr = ptr->pNext;  
  621.         }  
  622.           
  623.         if(pPre == NULL) // 应该插入到表头   
  624.         {  
  625.             pBuffer->pNext = pContext->pOutOfOrderReads;  
  626.             pContext->pOutOfOrderReads = pBuffer;  
  627.         }  
  628.         else            // 应该插入到表的中间   
  629.         {  
  630.             pBuffer->pNext = pPre->pNext;  
  631.             pPre->pNext = pBuffer; // [2009.8.9 mod Lostyears][old: pPre->pNext = pBuffer->pNext]   
  632.         }  
  633.     }  
  634.   
  635.     // 检查表头元素的序列号,如果与要读的序列号一致,就将它从表中移除,返回给用户   
  636.     CIOCPBuffer *ptr = pContext->pOutOfOrderReads;  
  637.     if(ptr != NULL && (ptr->nSequenceNumber == pContext->nCurrentReadSequence))  
  638.     {  
  639.         pContext->pOutOfOrderReads = ptr->pNext;  
  640.         return ptr;  
  641.     }  
  642.     return NULL;  
  643. }  
  644.   
  645.   
  646. BOOL CIOCPServer::PostAccept(CIOCPBuffer *pBuffer)  // 在监听套节字上投递Accept请求   
  647. {  
  648.         // 设置I/O类型   
  649.         pBuffer->nOperation = OP_ACCEPT;  
  650.   
  651.         // 投递此重叠I/O     
  652.         DWORD dwBytes;  
  653.         pBuffer->sClient = ::WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);  
  654.         BOOL b = m_lpfnAcceptEx(m_sListen,   
  655.             pBuffer->sClient,  
  656.             pBuffer->buff,   
  657.             pBuffer->nLen - ((sizeof(sockaddr_in) + 16) * 2), // [2010.5.16 bak Lostyears]如果这里为0, 表示不等待接收数据而通知, 如果这里改为0, 则GetAcceptExSockaddrs函数中的相应参数也得相应改   
  658.             sizeof(sockaddr_in) + 16,   
  659.             sizeof(sockaddr_in) + 16,   
  660.             &dwBytes,   
  661.             &pBuffer->ol);  
  662.         if(!b && ::WSAGetLastError() != WSA_IO_PENDING)  
  663.         {  
  664.             return FALSE;  
  665.         }  
  666.         return TRUE;  
  667. }  
  668.   
  669. BOOL CIOCPServer::PostRecv(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  670. {  
  671.     // 设置I/O类型   
  672.     pBuffer->nOperation = OP_READ;     
  673.       
  674.     ::EnterCriticalSection(&pContext->Lock);  
  675.   
  676.     // 设置序列号   
  677.     pBuffer->nSequenceNumber = pContext->nReadSequence;  
  678.   
  679.     // 投递此重叠I/O   
  680.     DWORD dwBytes;  
  681.     DWORD dwFlags = 0;  
  682.     WSABUF buf;  
  683.     buf.buf = pBuffer->buff;  
  684.     buf.len = pBuffer->nLen;  
  685.     if(::WSARecv(pContext->s, &buf, 1, &dwBytes, &dwFlags, &pBuffer->ol, NULL) != NO_ERROR)  
  686.     {  
  687.         if(::WSAGetLastError() != WSA_IO_PENDING)  
  688.         {  
  689.             ::LeaveCriticalSection(&pContext->Lock);  
  690.             return FALSE;  
  691.         }  
  692.     }  
  693.   
  694.     // 增加套节字上的重叠I/O计数和读序列号计数   
  695.   
  696.     pContext->nOutstandingRecv ++;  
  697.     pContext->nReadSequence ++;  
  698.   
  699.     ::LeaveCriticalSection(&pContext->Lock);  
  700.   
  701.     return TRUE;  
  702. }  
  703.   
  704. BOOL CIOCPServer::PostSend(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  705. {     
  706.     // 跟踪投递的发送的数量,防止用户仅发送数据而不接收,导致服务器抛出大量发送操作   
  707.     if(pContext->nOutstandingSend > m_nMaxSends)  
  708.         return FALSE;  
  709.   
  710.     // 设置I/O类型,增加套节字上的重叠I/O计数   
  711.     pBuffer->nOperation = OP_WRITE;  
  712.   
  713.     // 投递此重叠I/O   
  714.     DWORD dwBytes;  
  715.     DWORD dwFlags = 0;  
  716.     WSABUF buf;  
  717.     buf.buf = pBuffer->buff;  
  718.     buf.len = pBuffer->nLen;  
  719.     if(::WSASend(pContext->s,   
  720.             &buf, 1, &dwBytes, dwFlags, &pBuffer->ol, NULL) != NO_ERROR)  
  721.     {  
  722.         if(::WSAGetLastError() != WSA_IO_PENDING)  
  723.             return FALSE;  
  724.     }     
  725.       
  726.     // 增加套节字上的重叠I/O计数   
  727.     ::EnterCriticalSection(&pContext->Lock);  
  728.     pContext->nOutstandingSend ++;  
  729.     ::LeaveCriticalSection(&pContext->Lock);  
  730.   
  731.     return TRUE;  
  732. }  
  733.   
  734.   
  735. BOOL CIOCPServer::Start(int nPort, int nMaxConnections,   
  736.             int nMaxFreeBuffers, int nMaxFreeContexts, int nInitialReads)  
  737. {  
  738.     // 检查服务是否已经启动   
  739.     if(m_bServerStarted)  
  740.         return FALSE;  
  741.   
  742.     // 保存用户参数   
  743.     m_nPort = nPort;  
  744.     m_nMaxConnections = nMaxConnections;  
  745.     m_nMaxFreeBuffers = nMaxFreeBuffers;  
  746.     m_nMaxFreeContexts = nMaxFreeContexts;  
  747.     m_nInitialReads = nInitialReads;  
  748.   
  749.     // 初始化状态变量   
  750.     m_bShutDown = FALSE;  
  751.     m_bServerStarted = TRUE;  
  752.   
  753.   
  754.     // 创建监听套节字,绑定到本地端口,进入监听模式   
  755.     m_sListen = ::WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);  
  756.     SOCKADDR_IN si;  
  757.     si.sin_family = AF_INET;  
  758.     si.sin_port = ::ntohs(m_nPort);  
  759.     si.sin_addr.S_un.S_addr = INADDR_ANY;  
  760.     if(::bind(m_sListen, (sockaddr*)&si, sizeof(si)) == SOCKET_ERROR)  
  761.     {  
  762.         m_bServerStarted = FALSE;  
  763.         return FALSE;  
  764.     }  
  765.     ::listen(m_sListen, 200);  
  766.   
  767.     // 创建完成端口对象   
  768.     m_hCompletion = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0);  
  769.   
  770.     // 加载扩展函数AcceptEx   
  771.     GUID GuidAcceptEx = WSAID_ACCEPTEX;  
  772.     DWORD dwBytes;  
  773.     ::WSAIoctl(m_sListen,   
  774.         SIO_GET_EXTENSION_FUNCTION_POINTER,   
  775.         &GuidAcceptEx,   
  776.         sizeof(GuidAcceptEx),  
  777.         &m_lpfnAcceptEx,   
  778.         sizeof(m_lpfnAcceptEx),   
  779.         &dwBytes,   
  780.         NULL,   
  781.         NULL);  
  782.       
  783.     // 加载扩展函数GetAcceptExSockaddrs   
  784.     GUID GuidGetAcceptExSockaddrs = WSAID_GETACCEPTEXSOCKADDRS;  
  785.     ::WSAIoctl(m_sListen,  
  786.         SIO_GET_EXTENSION_FUNCTION_POINTER,  
  787.         &GuidGetAcceptExSockaddrs,  
  788.         sizeof(GuidGetAcceptExSockaddrs),  
  789.         &m_lpfnGetAcceptExSockaddrs,  
  790.         sizeof(m_lpfnGetAcceptExSockaddrs),  
  791.         &dwBytes,  
  792.         NULL,  
  793.         NULL  
  794.         );  
  795.       
  796.       
  797.     // 将监听套节字关联到完成端口,注意,这里为它传递的CompletionKey为0   
  798.     ::CreateIoCompletionPort((HANDLE)m_sListen, m_hCompletion, (DWORD)0, 0);  
  799.   
  800.     // 注册FD_ACCEPT事件。   
  801.     // 如果投递的AcceptEx I/O不够,线程会接收到FD_ACCEPT网络事件,说明应该投递更多的AcceptEx I/O   
  802.     WSAEventSelect(m_sListen, m_hAcceptEvent, FD_ACCEPT);  
  803.   
  804.     // 创建监听线程   
  805.     m_hListenThread = ::CreateThread(NULL, 0, _ListenThreadProc, this, 0, NULL);  
  806.       
  807.     return TRUE;  
  808. }  
  809.   
  810. void CIOCPServer::Shutdown()  
  811. {  
  812.     if(!m_bServerStarted)  
  813.         return;  
  814.   
  815.     // 通知监听线程,马上停止服务   
  816.     m_bShutDown = TRUE;  
  817.     ::SetEvent(m_hAcceptEvent);  
  818.     // 等待监听线程退出   
  819.     ::WaitForSingleObject(m_hListenThread, INFINITE);  
  820.     ::CloseHandle(m_hListenThread);  
  821.     m_hListenThread = NULL;  
  822.   
  823.     m_bServerStarted = FALSE;  
  824. }  
  825.   
  826. DWORD WINAPI CIOCPServer::_ListenThreadProc(LPVOID lpParam)  
  827. {  
  828.     CIOCPServer *pThis = (CIOCPServer*)lpParam;  
  829.   
  830.     // 先在监听套节字上投递几个Accept I/O   
  831.     CIOCPBuffer *pBuffer;  
  832.     for(int i=0; i<pThis->m_nInitialAccepts; i++)  
  833.     {  
  834.         pBuffer = pThis->AllocateBuffer(BUFFER_SIZE);  
  835.         if(pBuffer == NULL)  
  836.             return -1;  
  837.         pThis->InsertPendingAccept(pBuffer);  
  838.         pThis->PostAccept(pBuffer);  
  839.     }  
  840.   
  841.     // 构建事件对象数组,以便在上面调用WSAWaitForMultipleEvents函数   
  842.     HANDLE hWaitEvents[2 + MAX_THREAD];  
  843.     int nEventCount = 0;  
  844.     hWaitEvents[nEventCount ++] = pThis->m_hAcceptEvent;  
  845.     hWaitEvents[nEventCount ++] = pThis->m_hRepostEvent;  
  846.   
  847.     // 创建指定数量的工作线程在完成端口上处理I/O   
  848.     for(int i=0; i<MAX_THREAD; i++)  
  849.     {  
  850.         hWaitEvents[nEventCount ++] = ::CreateThread(NULL, 0, _WorkerThreadProc, pThis, 0, NULL);  
  851.     }  
  852.   
  853.     // 下面进入无限循环,处理事件对象数组中的事件   
  854.     while(TRUE)  
  855.     {  
  856.         int nIndex = ::WSAWaitForMultipleEvents(nEventCount, hWaitEvents, FALSE, 60*1000, FALSE);  
  857.       
  858.         // 首先检查是否要停止服务   
  859.         if(pThis->m_bShutDown || nIndex == WSA_WAIT_FAILED)  
  860.         {  
  861.             // 关闭所有连接   
  862.             pThis->CloseAllConnections();  
  863.             ::Sleep(0);     // 给I/O工作线程一个执行的机会   
  864.             // 关闭监听套节字   
  865.             ::closesocket(pThis->m_sListen);  
  866.             pThis->m_sListen = INVALID_SOCKET;  
  867.             ::Sleep(0);     // 给I/O工作线程一个执行的机会   
  868.   
  869.             // 通知所有I/O处理线程退出   
  870.             for(int i=2; i<MAX_THREAD + 2; i++)  
  871.             {     
  872.                 ::PostQueuedCompletionStatus(pThis->m_hCompletion, -1, 0, NULL);  
  873.             }  
  874.   
  875.             // 等待I/O处理线程退出   
  876.             ::WaitForMultipleObjects(MAX_THREAD, &hWaitEvents[2], TRUE, 5*1000);  
  877.   
  878.             for(int i=2; i<MAX_THREAD + 2; i++)  
  879.             {     
  880.                 ::CloseHandle(hWaitEvents[i]);  
  881.             }  
  882.           
  883.             ::CloseHandle(pThis->m_hCompletion);  
  884.   
  885.             pThis->FreeBuffers();  
  886.             pThis->FreeContexts();  
  887.             ::ExitThread(0);  
  888.         }     
  889.   
  890.         // 1)定时检查所有未返回的AcceptEx I/O的连接建立了多长时间   
  891.         if(nIndex == WSA_WAIT_TIMEOUT)  
  892.         {  
  893.             pBuffer = pThis->m_pPendingAccepts;  
  894.             while(pBuffer != NULL)  
  895.             {  
  896.                 int nSeconds;  
  897.                 int nLen = sizeof(nSeconds);  
  898.                 // 取得连接建立的时间   
  899.                 ::getsockopt(pBuffer->sClient,   
  900.                     SOL_SOCKET, SO_CONNECT_TIME, (char *)&nSeconds, &nLen);   
  901.                 // 如果超过2分钟客户还不发送初始数据,就让这个客户go away   
  902.                 if(nSeconds != -1 && nSeconds > 2*60)  
  903.                 {     
  904.                     closesocket(pBuffer->sClient);  
  905.                     pBuffer->sClient = INVALID_SOCKET;  
  906.                 }  
  907.   
  908.                 pBuffer = pBuffer->pNext;  
  909.             }  
  910.         }  
  911.         else  
  912.         {  
  913.             nIndex = nIndex - WAIT_OBJECT_0;  
  914.             WSANETWORKEVENTS ne;  
  915.             int nLimit=0;  
  916.             if(nIndex == 0)         // 2)m_hAcceptEvent事件对象受信,说明投递的Accept请求不够,需要增加   
  917.             {  
  918.                 ::WSAEnumNetworkEvents(pThis->m_sListen, hWaitEvents[nIndex], &ne);  
  919.                 if(ne.lNetworkEvents & FD_ACCEPT)  
  920.                 {  
  921.                     nLimit = 50;  // 增加的个数,这里设为50个   
  922.                 }  
  923.             }  
  924.             else if(nIndex == 1)    // 3)m_hRepostEvent事件对象受信,说明处理I/O的线程接受到新的客户   
  925.             {  
  926.                 nLimit = InterlockedExchange(&pThis->m_nRepostCount, 0);  
  927.             }  
  928.             else if(nIndex > 1)      // I/O服务线程退出,说明有错误发生,关闭服务器   
  929.             {  
  930.                 pThis->m_bShutDown = TRUE;  
  931.                 continue;  
  932.             }  
  933.   
  934.             // 投递nLimit个AcceptEx I/O请求   
  935.             int i = 0;  
  936.             while(i++ < nLimit && pThis->m_nPendingAcceptCount < pThis->m_nMaxAccepts)  
  937.             {  
  938.                 pBuffer = pThis->AllocateBuffer(BUFFER_SIZE);  
  939.                 if(pBuffer != NULL)  
  940.                 {  
  941.                     pThis->InsertPendingAccept(pBuffer);  
  942.                     pThis->PostAccept(pBuffer);  
  943.                 }  
  944.             }  
  945.         }  
  946.     }  
  947.     return 0;  
  948. }  
  949.   
  950. DWORD WINAPI CIOCPServer::_WorkerThreadProc(LPVOID lpParam)  
  951. {  
  952. #ifdef _DEBUG   
  953.             ::OutputDebugString("   WorkerThread 启动...  ");  
  954. #endif // _DEBUG   
  955.   
  956.     CIOCPServer *pThis = (CIOCPServer*)lpParam;  
  957.   
  958.     CIOCPBuffer *pBuffer;  
  959.     DWORD dwKey;  
  960.     DWORD dwTrans;  
  961.     LPOVERLAPPED lpol;  
  962.     while(TRUE)  
  963.     {  
  964.         // 在关联到此完成端口的所有套节字上等待I/O完成   
  965.         BOOL bOK = ::GetQueuedCompletionStatus(pThis->m_hCompletion,   
  966.                     &dwTrans, (LPDWORD)&dwKey, (LPOVERLAPPED*)&lpol, WSA_INFINITE);  
  967.   
  968.         if(dwTrans == -1) // 用户通知退出   
  969.         {  
  970. #ifdef _DEBUG   
  971.             ::OutputDebugString("   WorkerThread 退出  ");  
  972. #endif // _DEBUG   
  973.             ::ExitThread(0);  
  974.         }  
  975.   
  976.   
  977.         pBuffer = CONTAINING_RECORD(lpol, CIOCPBuffer, ol); // [2009.8.9 bak Lostyears][lpol作为CIOCPBuffer的ol成员,由其地址取CIOCPBuffer实例首地址]   
  978.         int nError = NO_ERROR;  
  979.         if(!bOK)                        // 在此套节字上有错误发生   
  980.         {  
  981.             SOCKET s;  
  982.             if(pBuffer->nOperation == OP_ACCEPT)  
  983.             {  
  984.                 s = pThis->m_sListen;  
  985.             }  
  986.             else  
  987.             {  
  988.                 if(dwKey == 0)  
  989.                     break;  
  990.                 s = ((CIOCPContext*)dwKey)->s;  
  991.             }  
  992.             DWORD dwFlags = 0;  
  993.             if(!::WSAGetOverlappedResult(s, &pBuffer->ol, &dwTrans, FALSE, &dwFlags))  
  994.             {  
  995.                 nError = ::WSAGetLastError();  
  996.             }  
  997.         }  
  998.         pThis->HandleIO(dwKey, pBuffer, dwTrans, nError);  
  999.     }  
  1000.   
  1001. #ifdef _DEBUG   
  1002.             ::OutputDebugString("   WorkerThread 退出  ");  
  1003. #endif // _DEBUG   
  1004.     return 0;  
  1005. }  
  1006.   
  1007.   
  1008. void CIOCPServer::HandleIO(DWORD dwKey, CIOCPBuffer *pBuffer, DWORD dwTrans, int nError)  
  1009. {  
  1010.     CIOCPContext *pContext = (CIOCPContext *)dwKey;  
  1011.   
  1012. #ifdef _DEBUG   
  1013.             ::OutputDebugString("   HandleIO...  ");  
  1014. #endif // _DEBUG   
  1015.       
  1016.     // 1)首先减少套节字上的未决I/O计数   
  1017.     if(pContext != NULL)  
  1018.     {  
  1019.         ::EnterCriticalSection(&pContext->Lock);  
  1020.           
  1021.         if(pBuffer->nOperation == OP_READ)  
  1022.             pContext->nOutstandingRecv --;  
  1023.         else if(pBuffer->nOperation == OP_WRITE)  
  1024.             pContext->nOutstandingSend --;  
  1025.           
  1026.         ::LeaveCriticalSection(&pContext->Lock);  
  1027.           
  1028.         // 2)检查套节字是否已经被我们关闭 [2009.8.9 bak Lostyears][如果关闭则释放剩下的未决IO]   
  1029.         if(pContext->bClosing)   
  1030.         {  
  1031. #ifdef _DEBUG   
  1032.             ::OutputDebugString("   检查到套节字已经被我们关闭  ");  
  1033. #endif // _DEBUG   
  1034.             if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)  
  1035.             {         
  1036.                 ReleaseContext(pContext);  
  1037.             }  
  1038.             // 释放已关闭套节字的未决I/O   
  1039.             ReleaseBuffer(pBuffer);   
  1040.             return;  
  1041.         }  
  1042.     }  
  1043.     else  
  1044.     {  
  1045.         RemovePendingAccept(pBuffer); // [2009.8.9 bak Lostyears][sListen关联了iocp, 关联时dwKey为0, 所以当有新连接发送数据时会执行到此]   
  1046.     }  
  1047.   
  1048.     // 3)检查套节字上发生的错误,如果有的话,通知用户,然后关闭套节字   
  1049.     if(nError != NO_ERROR)  
  1050.     {  
  1051.         if(pBuffer->nOperation != OP_ACCEPT)  
  1052.         {  
  1053.             NotifyConnectionError(pContext, pBuffer, nError);  
  1054.             CloseAConnection(pContext);  
  1055.             if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)  
  1056.             {         
  1057.                 ReleaseContext(pContext);  
  1058.             }  
  1059. #ifdef _DEBUG   
  1060.             ::OutputDebugString("   检查到客户套节字上发生错误  ");  
  1061. #endif // _DEBUG   
  1062.         }  
  1063.         else // 在监听套节字上发生错误,也就是监听套节字处理的客户出错了   
  1064.         {  
  1065.             // 客户端出错,释放I/O缓冲区   
  1066.             if(pBuffer->sClient != INVALID_SOCKET)  
  1067.             {  
  1068.                 ::closesocket(pBuffer->sClient);  
  1069.                 pBuffer->sClient = INVALID_SOCKET;  
  1070.             }  
  1071. #ifdef _DEBUG   
  1072.             ::OutputDebugString("   检查到监听套节字上发生错误  ");  
  1073. #endif // _DEBUG   
  1074.         }  
  1075.   
  1076.         ReleaseBuffer(pBuffer);  
  1077.         return;  
  1078.     }  
  1079.   
  1080.   
  1081.     // 开始处理   
  1082.     if(pBuffer->nOperation == OP_ACCEPT)  
  1083.     {  
  1084.         if(dwTrans == 0) // [2010.5.16 bak Lostyears]如果AcceptEx的数据接收缓冲区设为0, 一连接上就会执行到这   
  1085.         {  
  1086. #ifdef _DEBUG   
  1087.             ::OutputDebugString("   监听套节字上客户端关闭  ");  
  1088. #endif // _DEBUG   
  1089.               
  1090.             if(pBuffer->sClient != INVALID_SOCKET)  
  1091.             {  
  1092.                 ::closesocket(pBuffer->sClient);  
  1093.                 pBuffer->sClient = INVALID_SOCKET;  
  1094.             }  
  1095.         }  
  1096.         else  
  1097.         {  
  1098.             // 为新接受的连接申请客户上下文对象   
  1099.         CIOCPContext *pClient = AllocateContext(pBuffer->sClient);  
  1100.             if(pClient != NULL)  
  1101.             {  
  1102.                 if(AddAConnection(pClient))  
  1103.                 {     
  1104.                     // 取得客户地址   
  1105.                     int nLocalLen, nRmoteLen;  
  1106.                     LPSOCKADDR pLocalAddr, pRemoteAddr;  
  1107.                     m_lpfnGetAcceptExSockaddrs(  
  1108.                         pBuffer->buff,  
  1109.                         pBuffer->nLen - ((sizeof(sockaddr_in) + 16) * 2), // [2010.5.16 bak Lostyears]和AcceptEx相应参数对应   
  1110.                         sizeof(sockaddr_in) + 16,  
  1111.                         sizeof(sockaddr_in) + 16,  
  1112.                         (SOCKADDR **)&pLocalAddr,  
  1113.                         &nLocalLen,  
  1114.                         (SOCKADDR **)&pRemoteAddr,  
  1115.                         &nRmoteLen);  
  1116.                     memcpy(&pClient->addrLocal, pLocalAddr, nLocalLen);  
  1117.                     memcpy(&pClient->addrRemote, pRemoteAddr, nRmoteLen);  
  1118.   
  1119.                     // [2010.1.15 add Lostyears][加入KeepAlive机制]   
  1120.                     BOOL bKeepAlive = TRUE;  
  1121.                     int nRet = ::setsockopt(pClient->s, SOL_SOCKET, SO_KEEPALIVE, (char*)&bKeepAlive, sizeof(bKeepAlive));  
  1122.                     if (nRet == SOCKET_ERROR)  
  1123.                     {  
  1124.                         CloseAConnection(pClient);  
  1125.                     }  
  1126.                     else  
  1127.                     {  
  1128.                         // 设置KeepAlive参数   
  1129.                         tcp_keepalive alive_in  = {0};  
  1130.                         tcp_keepalive alive_out = {0};  
  1131.                         alive_in.keepalivetime      = 5000; // 开始首次KeepAlive探测前的TCP空闲时间   
  1132.                         alive_in.keepaliveinterval  = 1000; // 两次KeepAlive探测间的时间间隔   
  1133.                         alive_in.onoff  = TRUE;  
  1134.                         unsigned long ulBytesReturn = 0;  
  1135.                         nRet = ::WSAIoctl(pClient->s, SIO_KEEPALIVE_VALS, &alive_in, sizeof(alive_in),  
  1136.                             &alive_out, sizeof(alive_out), &ulBytesReturn, NULL, NULL);  
  1137.                         if (nRet == SOCKET_ERROR)  
  1138.                         {  
  1139.                             CloseAConnection(pClient);  
  1140.                         }  
  1141.                         else  
  1142.                         {  
  1143.                             // 关联新连接到完成端口对象   
  1144.                             ::CreateIoCompletionPort((HANDLE)pClient->s, m_hCompletion, (DWORD)pClient, 2);  
  1145.                               
  1146.                             // 通知用户   
  1147.                             pBuffer->nLen = dwTrans;  
  1148.                             OnConnectionEstablished(pClient, pBuffer);  
  1149.                               
  1150.                             // 向新连接投递几个Read请求,这些空间在套节字关闭或出错时释放   
  1151.                             for(int i=0; i<m_nInitialReads; i++) // [2009.8.21 mod Lostyears][将常量值改为m_nInitialReads]   
  1152.                             {  
  1153.                                 CIOCPBuffer *p = AllocateBuffer(BUFFER_SIZE);  
  1154.                                 if(p != NULL)  
  1155.                                 {  
  1156.                                     if(!PostRecv(pClient, p))  
  1157.                                     {  
  1158.                                         CloseAConnection(pClient);  
  1159.                                         break;  
  1160.                                     }  
  1161.                                 }  
  1162.                             }  
  1163.                         }  
  1164.                     }  
  1165.                       
  1166.                     //// 关联新连接到完成端口对象   
  1167.                     //::CreateIoCompletionPort((HANDLE)pClient->s, m_hCompletion, (DWORD)pClient, 0);   
  1168.                     //   
  1169.                     //// 通知用户   
  1170.                     //pBuffer->nLen = dwTrans;   
  1171.                     //OnConnectionEstablished(pClient, pBuffer);   
  1172.                     //   
  1173.                     //// 向新连接投递几个Read请求,这些空间在套节字关闭或出错时释放   
  1174.                     //for(int i=0; i<m_nInitialReads; i++) // [2009.8.22 mod Lostyears][old: i<5]   
  1175.                     //{   
  1176.                     //  CIOCPBuffer *p = AllocateBuffer(BUFFER_SIZE);   
  1177.                     //  if(p != NULL)   
  1178.                     //  {   
  1179.                     //      if(!PostRecv(pClient, p))   
  1180.                     //      {   
  1181.                     //          CloseAConnection(pClient);   
  1182.                     //          break;   
  1183.                     //      }   
  1184.                     //  }   
  1185.                     //}   
  1186.                 }  
  1187.                 else    // 连接数量已满,关闭连接   
  1188.                 {  
  1189.                     CloseAConnection(pClient);  
  1190.                     ReleaseContext(pClient);  
  1191.                 }  
  1192.             }  
  1193.             else  
  1194.             {  
  1195.                 // 资源不足,关闭与客户的连接即可   
  1196.                 ::closesocket(pBuffer->sClient);  
  1197.                 pBuffer->sClient = INVALID_SOCKET;  
  1198.             }  
  1199.         }  
  1200.           
  1201.         // Accept请求完成,释放I/O缓冲区   
  1202.         ReleaseBuffer(pBuffer);   
  1203.   
  1204.         // 通知监听线程继续再投递一个Accept请求   
  1205.         ::InterlockedIncrement(&m_nRepostCount);  
  1206.         ::SetEvent(m_hRepostEvent);  
  1207.     }  
  1208.     else if(pBuffer->nOperation == OP_READ)  
  1209.     {  
  1210.         if(dwTrans == 0)    // 对方关闭套节字   
  1211.         {  
  1212.             // 先通知用户   
  1213.             pBuffer->nLen = 0;  
  1214.             NotifyConnectionClosing(pContext, pBuffer);   
  1215.   
  1216.             // 再关闭连接   
  1217.             CloseAConnection(pContext);  
  1218.             // 释放客户上下文和缓冲区对象   
  1219.             if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)  
  1220.             {         
  1221.                 ReleaseContext(pContext);  
  1222.             }  
  1223.             ReleaseBuffer(pBuffer);   
  1224.         }  
  1225.         else  
  1226.         {  
  1227.             pBuffer->nLen = dwTrans;  
  1228.             // 按照I/O投递的顺序读取接收到的数据   
  1229.             CIOCPBuffer *p = GetNextReadBuffer(pContext, pBuffer);  
  1230.             while(p != NULL)  
  1231.             {  
  1232.                 // 通知用户   
  1233.                 OnReadCompleted(pContext, p);  
  1234.                 // 增加要读的序列号的值   
  1235.                 ::InterlockedIncrement((LONG*)&pContext->nCurrentReadSequence);  
  1236.                 // 释放这个已完成的I/O   
  1237.                 ReleaseBuffer(p);  
  1238.                 p = GetNextReadBuffer(pContext, NULL);  
  1239.             }  
  1240.   
  1241.             // 继续投递一个新的接收请求   
  1242.             pBuffer = AllocateBuffer(BUFFER_SIZE);  
  1243.             if(pBuffer == NULL || !PostRecv(pContext, pBuffer))  
  1244.             {  
  1245.                 CloseAConnection(pContext);  
  1246.             }  
  1247.         }  
  1248.     }  
  1249.     else if(pBuffer->nOperation == OP_WRITE)  
  1250.     {  
  1251.   
  1252.         if(dwTrans == 0)    // 对方关闭套节字   
  1253.         {  
  1254.             // 先通知用户   
  1255.             pBuffer->nLen = 0;  
  1256.             NotifyConnectionClosing(pContext, pBuffer);   
  1257.   
  1258.             // 再关闭连接   
  1259.             CloseAConnection(pContext);  
  1260.   
  1261.             // 释放客户上下文和缓冲区对象   
  1262.             if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)  
  1263.             {         
  1264.                 ReleaseContext(pContext);  
  1265.             }  
  1266.             ReleaseBuffer(pBuffer);   
  1267.         }  
  1268.         else  
  1269.         {  
  1270.             // 写操作完成,通知用户   
  1271.             pBuffer->nLen = dwTrans;  
  1272.             OnWriteCompleted(pContext, pBuffer);  
  1273.             // 释放SendText函数申请的缓冲区   
  1274.             ReleaseBuffer(pBuffer);  
  1275.         }  
  1276.     }  
  1277. }  
  1278.   
  1279. // 当套件字关闭或出错时通知   
  1280. void CIOCPServer::NotifyConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1281. {  
  1282.     ::EnterCriticalSection(&m_CloseOrErrLock);  
  1283.     if (!pContext->bNotifyCloseOrError)  
  1284.     {  
  1285.         pContext->bNotifyCloseOrError = true;  
  1286.         OnConnectionClosing(pContext, pBuffer);  
  1287.     }  
  1288.     ::LeaveCriticalSection(&m_CloseOrErrLock);  
  1289. }  
  1290.   
  1291. void CIOCPServer::NotifyConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError)  
  1292. {  
  1293.     ::EnterCriticalSection(&m_CloseOrErrLock);  
  1294.     if (!pContext->bNotifyCloseOrError)  
  1295.     {  
  1296.         pContext->bNotifyCloseOrError = true;  
  1297.         OnConnectionError(pContext, pBuffer, nError);  
  1298.     }  
  1299.     ::LeaveCriticalSection(&m_CloseOrErrLock);  
  1300. }  
  1301.   
  1302.   
  1303.   
  1304. BOOL CIOCPServer::SendText(CIOCPContext *pContext, char *pszText, int nLen)  
  1305. {  
  1306.     CIOCPBuffer *pBuffer = AllocateBuffer(nLen);  
  1307.     if(pBuffer != NULL)  
  1308.     {  
  1309.         memcpy(pBuffer->buff, pszText, nLen);  
  1310.         return PostSend(pContext, pBuffer);  
  1311.     }  
  1312.     return FALSE;  
  1313. }  
  1314.   
  1315.   
  1316. void CIOCPServer::OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1317. {  
  1318. }  
  1319.   
  1320. void CIOCPServer::OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1321. {  
  1322. }  
  1323.   
  1324.   
  1325. void CIOCPServer::OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1326. {  
  1327. }  
  1328.   
  1329. void CIOCPServer::OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1330. {  
  1331. }  
  1332.   
  1333. void CIOCPServer::OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError)  
  1334. {  
  1335. }  
  1336. ////////////////////////////////////////////////   
  1337. // iocpserver.cpp文件   
  1338.   
  1339.   
  1340. // CIOCPServer类的测试程序   
  1341.   
  1342. #include "iocp.h"   
  1343. #include <stdio.h>   
  1344. #include <windows.h>   
  1345.   
  1346. class CMyServer : public CIOCPServer  
  1347. {  
  1348. public:  
  1349.   
  1350.     void OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1351.     {  
  1352.         printf("接收到一个新的连接(%d): %s ",   
  1353.                     GetCurrentConnection(), ::inet_ntoa(pContext->addrRemote.sin_addr));  
  1354.         printf("接受到一个数据包, 其大小为: %d字节 ", pBuffer->nLen);  
  1355.   
  1356.         SendText(pContext, pBuffer->buff, pBuffer->nLen);  
  1357.     }  
  1358.   
  1359.     void OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1360.     {  
  1361.         printf("一个连接关闭 ");  
  1362.     }  
  1363.   
  1364.     void OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError)  
  1365.     {  
  1366.         printf("一个连接发生错误: %d ", nError);  
  1367.     }  
  1368.   
  1369.     void OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1370.     {  
  1371.         printf("接受到一个数据包, 其大小为: %d字节 ", pBuffer->nLen);  
  1372.         SendText(pContext, pBuffer->buff, pBuffer->nLen);  
  1373.     }  
  1374.       
  1375.     void OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)  
  1376.     {  
  1377.         printf("一个数据包发送成功, 其大小为: %d字节  ", pBuffer->nLen);  
  1378.     }  
  1379. };  
  1380.   
  1381. void main()  
  1382. {  
  1383.     CMyServer *pServer = new CMyServer;  
  1384.   
  1385.     // 开启服务   
  1386.     if(pServer->Start())  
  1387.     {  
  1388.         printf("服务器开启成功... ");  
  1389.     }  
  1390.     else  
  1391.     {  
  1392.         printf("服务器开启失败! ");  
  1393.         return;  
  1394.     }  
  1395.   
  1396.     // 创建事件对象,让ServerShutdown程序能够关闭自己   
  1397.     HANDLE hEvent = ::CreateEvent(NULL, FALSE, FALSE, "ShutdownEvent");  
  1398.     ::WaitForSingleObject(hEvent, INFINITE);  
  1399.     ::CloseHandle(hEvent);  
  1400.   
  1401.     // 关闭服务   
  1402.     pServer->Shutdown();  
  1403.     delete pServer;  
  1404.   
  1405.     printf("服务器关闭  ");  
  1406.   
  1407. }  
////////////////////////////////////////
// IOCP.h文件

#ifndef __IOCP_H__
#define __IOCP_H__

#include <winsock2.h>
#include <windows.h>
#include <Mswsock.h>

#define BUFFER_SIZE 1024*4	// I/O请求的缓冲区大小
#define MAX_THREAD	2		// I/O服务线程的数量


// 这是per-I/O数据。它包含了在套节字上处理I/O操作的必要信息
struct CIOCPBuffer
{
	WSAOVERLAPPED ol;

	SOCKET sClient;			// AcceptEx接收的客户方套节字

	char *buff;				// I/O操作使用的缓冲区
	int nLen;				// buff缓冲区(使用的)大小

	ULONG nSequenceNumber;	// 此I/O的序列号

	int nOperation;			// 操作类型
#define OP_ACCEPT	1
#define OP_WRITE	2
#define OP_READ		3

	CIOCPBuffer *pNext;
};

// 这是per-Handle数据。它包含了一个套节字的信息
struct CIOCPContext
{
	SOCKET s;						// 套节字句柄

	SOCKADDR_IN addrLocal;			// 连接的本地地址
	SOCKADDR_IN addrRemote;			// 连接的远程地址

	BOOL bClosing;					// 套节字是否关闭

	int nOutstandingRecv;			// 此套节字上抛出的重叠操作的数量
	int nOutstandingSend;


	ULONG nReadSequence;			// 安排给接收的下一个序列号
	ULONG nCurrentReadSequence;		// 当前要读的序列号
	CIOCPBuffer *pOutOfOrderReads;	// 记录没有按顺序完成的读I/O

	CRITICAL_SECTION Lock;			// 保护这个结构

	bool bNotifyCloseOrError;		// [2009.8.22 add Lostyears][当套接字关闭或出错时是否已通知过]

	CIOCPContext *pNext;
};


class CIOCPServer   // 处理线程
{
public:
	CIOCPServer();
	~CIOCPServer();

	// 开始服务
	BOOL Start(int nPort = 4567, int nMaxConnections = 2000, 
			int nMaxFreeBuffers = 200, int nMaxFreeContexts = 100, int nInitialReads = 4); 
	// 停止服务
	void Shutdown();

	// 关闭一个连接和关闭所有连接
	void CloseAConnection(CIOCPContext *pContext);
	void CloseAllConnections();	

	// 取得当前的连接数量
	ULONG GetCurrentConnection() { return m_nCurrentConnection; }

	// 向指定客户发送文本
	BOOL SendText(CIOCPContext *pContext, char *pszText, int nLen); 

protected:

	// 申请和释放缓冲区对象
	CIOCPBuffer *AllocateBuffer(int nLen);
	void ReleaseBuffer(CIOCPBuffer *pBuffer);

	// 申请和释放套节字上下文
	CIOCPContext *AllocateContext(SOCKET s);
	void ReleaseContext(CIOCPContext *pContext);

	// 释放空闲缓冲区对象列表和空闲上下文对象列表
	void FreeBuffers();
	void FreeContexts();

	// 向连接列表中添加一个连接
	BOOL AddAConnection(CIOCPContext *pContext);

	// 插入和移除未决的接受请求
	BOOL InsertPendingAccept(CIOCPBuffer *pBuffer);
	BOOL RemovePendingAccept(CIOCPBuffer *pBuffer);

	// 取得下一个要读取的
	CIOCPBuffer *GetNextReadBuffer(CIOCPContext *pContext, CIOCPBuffer *pBuffer);


	// 投递接受I/O、发送I/O、接收I/O
	BOOL PostAccept(CIOCPBuffer *pBuffer);
	BOOL PostSend(CIOCPContext *pContext, CIOCPBuffer *pBuffer);
	BOOL PostRecv(CIOCPContext *pContext, CIOCPBuffer *pBuffer);

	void HandleIO(DWORD dwKey, CIOCPBuffer *pBuffer, DWORD dwTrans, int nError);


	// [2009.8.22 add Lostyears]
	// 当套件字关闭或出错时通知
	void NotifyConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer);
	void NotifyConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError);

		// 事件通知函数
	// 建立了一个新的连接
	virtual void OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer);
	// 一个连接关闭
	virtual void OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer);
	// 在一个连接上发生了错误
	virtual void OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError);
	// 一个连接上的读操作完成
	virtual void OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer);
	// 一个连接上的写操作完成
	virtual void OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer);

protected:

	// 记录空闲结构信息
	CIOCPBuffer *m_pFreeBufferList;
	CIOCPContext *m_pFreeContextList;
	int m_nFreeBufferCount;
	int m_nFreeContextCount;	
	CRITICAL_SECTION m_FreeBufferListLock;
	CRITICAL_SECTION m_FreeContextListLock;

	// 记录抛出的Accept请求
	CIOCPBuffer *m_pPendingAccepts;   // 抛出请求列表。
	long m_nPendingAcceptCount;
	CRITICAL_SECTION m_PendingAcceptsLock;

	// 记录连接列表
	CIOCPContext *m_pConnectionList;
	int m_nCurrentConnection;
	CRITICAL_SECTION m_ConnectionListLock;

	// 用于投递Accept请求
	HANDLE m_hAcceptEvent;
	HANDLE m_hRepostEvent;
	LONG m_nRepostCount;

	int m_nPort;				// 服务器监听的端口

	int m_nInitialAccepts;		// 开始时抛出的异步接收投递数
	int m_nInitialReads;
	int m_nMaxAccepts;			// 抛出的异步接收投递数最大值
	int m_nMaxSends;			// 抛出的异步发送投递数最大值(跟踪投递的发送的数量,防止用户仅发送数据而不接收,导致服务器抛出大量发送操作)
	int m_nMaxFreeBuffers;		// 内存池中容纳的最大内存块数(超过该数将在物理上释放内存池)
	int m_nMaxFreeContexts;		// 上下文[套接字信息]内存池中容纳的最大上下文内存块数(超过该数将在物理上释放上下文内存池)
	int m_nMaxConnections;		// 最大连接数

	HANDLE m_hListenThread;			// 监听线程
	HANDLE m_hCompletion;			// 完成端口句柄
	SOCKET m_sListen;				// 监听套节字句柄
	LPFN_ACCEPTEX m_lpfnAcceptEx;	// AcceptEx函数地址
	LPFN_GETACCEPTEXSOCKADDRS m_lpfnGetAcceptExSockaddrs; // GetAcceptExSockaddrs函数地址

	BOOL m_bShutDown;		// 用于通知监听线程退出
	BOOL m_bServerStarted;	// 记录服务是否启动

	CRITICAL_SECTION m_CloseOrErrLock;	// [2009.9.1 add Lostyears]

private:	// 线程函数
	static DWORD WINAPI _ListenThreadProc(LPVOID lpParam);
	static DWORD WINAPI _WorkerThreadProc(LPVOID lpParam);
};


#endif // __IOCP_H__
//////////////////////////////////////////////////
// IOCP.cpp文件

#include "iocp.h"
#pragma comment(lib, "WS2_32.lib")
#include <stdio.h>
#include <mstcpip.h>

CIOCPServer::CIOCPServer()
{
	// 列表
	m_pFreeBufferList = NULL;
	m_pFreeContextList = NULL;	
	m_pPendingAccepts = NULL;
	m_pConnectionList = NULL;

	m_nFreeBufferCount = 0;
	m_nFreeContextCount = 0;
	m_nPendingAcceptCount = 0;
	m_nCurrentConnection = 0;

	::InitializeCriticalSection(&m_FreeBufferListLock);
	::InitializeCriticalSection(&m_FreeContextListLock);
	::InitializeCriticalSection(&m_PendingAcceptsLock);
	::InitializeCriticalSection(&m_ConnectionListLock);
	::InitializeCriticalSection(&m_CloseOrErrLock);	// [2009.9.1 add Lostyears]

	// Accept请求
	m_hAcceptEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
	m_hRepostEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
	m_nRepostCount = 0;

	m_nPort = 4567;

	m_nInitialAccepts = 10;
	m_nInitialReads = 4;
	m_nMaxAccepts = 100;
	m_nMaxSends = 20;
	m_nMaxFreeBuffers = 200;
	m_nMaxFreeContexts = 100;
	m_nMaxConnections = 2000;

	m_hListenThread = NULL;
	m_hCompletion = NULL;
	m_sListen = INVALID_SOCKET;
	m_lpfnAcceptEx = NULL;
	m_lpfnGetAcceptExSockaddrs = NULL;

	m_bShutDown = FALSE;
	m_bServerStarted = FALSE;
	
	// 初始化WS2_32.dll
	WSADATA wsaData;
	WORD sockVersion = MAKEWORD(2, 2);
	::WSAStartup(sockVersion, &wsaData);
}

CIOCPServer::~CIOCPServer()
{
	Shutdown();

	if(m_sListen != INVALID_SOCKET)
		::closesocket(m_sListen);
	if(m_hListenThread != NULL)
		::CloseHandle(m_hListenThread);

	::CloseHandle(m_hRepostEvent);
	::CloseHandle(m_hAcceptEvent);

	::DeleteCriticalSection(&m_FreeBufferListLock);
	::DeleteCriticalSection(&m_FreeContextListLock);
	::DeleteCriticalSection(&m_PendingAcceptsLock);
	::DeleteCriticalSection(&m_ConnectionListLock);
	::DeleteCriticalSection(&m_CloseOrErrLock); // [2009.9.1 add Lostyears]

	::WSACleanup();	
}


///////////////////////////////////
// 自定义帮助函数

CIOCPBuffer *CIOCPServer::AllocateBuffer(int nLen)
{
	CIOCPBuffer *pBuffer = NULL;
	if(nLen > BUFFER_SIZE)
		return NULL;

	// 为缓冲区对象申请内存
	::EnterCriticalSection(&m_FreeBufferListLock);
	if(m_pFreeBufferList == NULL)  // 内存池为空,申请新的内存
	{
		pBuffer = (CIOCPBuffer *)::HeapAlloc(GetProcessHeap(), 
						HEAP_ZERO_MEMORY, sizeof(CIOCPBuffer) + BUFFER_SIZE);
	}
	else	// 从内存池中取一块来使用
	{
		pBuffer = m_pFreeBufferList;
		m_pFreeBufferList = m_pFreeBufferList->pNext;	
		pBuffer->pNext = NULL;
		m_nFreeBufferCount --;
	}
	::LeaveCriticalSection(&m_FreeBufferListLock);

	// 初始化新的缓冲区对象
	if(pBuffer != NULL)
	{
		pBuffer->buff = (char*)(pBuffer + 1);
		pBuffer->nLen = nLen;
		//::ZeroMemory(pBuffer->buff, pBuffer->nLen);
	}
	return pBuffer;
}

void CIOCPServer::ReleaseBuffer(CIOCPBuffer *pBuffer)
{
	::EnterCriticalSection(&m_FreeBufferListLock);

	if(m_nFreeBufferCount < m_nMaxFreeBuffers)	// 将要释放的内存添加到空闲列表中 [2010.5.15 mod Lostyears]old:m_nFreeBufferCount <= m_nMaxFreeBuffers
	{
		memset(pBuffer, 0, sizeof(CIOCPBuffer) + BUFFER_SIZE);
		pBuffer->pNext = m_pFreeBufferList;
		m_pFreeBufferList = pBuffer;

		m_nFreeBufferCount ++ ;
	}
	else			// 已经达到最大值,真正的释放内存
	{
		::HeapFree(::GetProcessHeap(), 0, pBuffer);
	}

	::LeaveCriticalSection(&m_FreeBufferListLock);
}


CIOCPContext *CIOCPServer::AllocateContext(SOCKET s)
{
	CIOCPContext *pContext;

	// 申请一个CIOCPContext对象
	::EnterCriticalSection(&m_FreeContextListLock);
	if(m_pFreeContextList == NULL)
	{
		pContext = (CIOCPContext *)
				::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CIOCPContext)); 

		::InitializeCriticalSection(&pContext->Lock);
	}
	else	
	{
		// 在空闲列表中申请
		pContext = m_pFreeContextList;
		m_pFreeContextList = m_pFreeContextList->pNext;
		pContext->pNext = NULL;

		m_nFreeContextCount --; // [2009.8.9 mod Lostyears][old: m_nFreeBufferCount--] 
	}

	::LeaveCriticalSection(&m_FreeContextListLock);

	// 初始化对象成员
	if(pContext != NULL)
	{
		pContext->s = s;

		// [2009.8.22 add Lostyears]
		pContext->bNotifyCloseOrError = false;
	}

	return pContext;
}

void CIOCPServer::ReleaseContext(CIOCPContext *pContext)
{
	if(pContext->s != INVALID_SOCKET)
		::closesocket(pContext->s);

	// 首先释放(如果有的话)此套节字上的没有按顺序完成的读I/O的缓冲区
	CIOCPBuffer *pNext;
	while(pContext->pOutOfOrderReads != NULL)
	{
		pNext = pContext->pOutOfOrderReads->pNext;
		ReleaseBuffer(pContext->pOutOfOrderReads);
		pContext->pOutOfOrderReads = pNext;
	}

	::EnterCriticalSection(&m_FreeContextListLock);
	
	if(m_nFreeContextCount < m_nMaxFreeContexts) // 添加到空闲列表 [2010.4.10 mod Lostyears][old: m_nFreeContextCount <= m_nMaxFreeContexts]如果m_nFreeContextCount==m_nMaxFreeContexts时,会在下一次导致m_nFreeContextCount>m_nMaxFreeContexts

	{
		// 先将关键代码段变量保存到一个临时变量中
		CRITICAL_SECTION cstmp = pContext->Lock;

		// 将要释放的上下文对象初始化为0
		memset(pContext, 0, sizeof(CIOCPContext));

		// 再放会关键代码段变量,将要释放的上下文对象添加到空闲列表的表头
		pContext->Lock = cstmp;
		pContext->pNext = m_pFreeContextList;
		m_pFreeContextList = pContext;
		
		// 更新计数
		m_nFreeContextCount ++;
	}
	else // 已经达到最大值,真正地释放
	{
		::DeleteCriticalSection(&pContext->Lock);
		::HeapFree(::GetProcessHeap(), 0, pContext);
		pContext = NULL;
	}

	::LeaveCriticalSection(&m_FreeContextListLock);
}

void CIOCPServer::FreeBuffers()
{
	// 遍历m_pFreeBufferList空闲列表,释放缓冲区池内存
	::EnterCriticalSection(&m_FreeBufferListLock);

	CIOCPBuffer *pFreeBuffer = m_pFreeBufferList;
	CIOCPBuffer *pNextBuffer;
	while(pFreeBuffer != NULL)
	{
		pNextBuffer = pFreeBuffer->pNext;
		if(!::HeapFree(::GetProcessHeap(), 0, pFreeBuffer))
		{
#ifdef _DEBUG
			::OutputDebugString("  FreeBuffers释放内存出错!");
#endif // _DEBUG
			break;
		}
		pFreeBuffer = pNextBuffer;
	}
	m_pFreeBufferList = NULL;
	m_nFreeBufferCount = 0;

	::LeaveCriticalSection(&m_FreeBufferListLock);
}

void CIOCPServer::FreeContexts()
{
	// 遍历m_pFreeContextList空闲列表,释放缓冲区池内存
	::EnterCriticalSection(&m_FreeContextListLock);
	
	CIOCPContext *pFreeContext = m_pFreeContextList;
	CIOCPContext *pNextContext;
	while(pFreeContext != NULL)
	{
		pNextContext = pFreeContext->pNext;
		
		::DeleteCriticalSection(&pFreeContext->Lock);
		if(!::HeapFree(::GetProcessHeap(), 0, pFreeContext))
		{
#ifdef _DEBUG
			::OutputDebugString("  FreeBuffers释放内存出错!");
#endif // _DEBUG
			break;
		}
		pFreeContext = pNextContext;
	}
	m_pFreeContextList = NULL;
	m_nFreeContextCount = 0;

	::LeaveCriticalSection(&m_FreeContextListLock);
}


BOOL CIOCPServer::AddAConnection(CIOCPContext *pContext)
{
	// 向客户连接列表添加一个CIOCPContext对象

	::EnterCriticalSection(&m_ConnectionListLock);
	if(m_nCurrentConnection < m_nMaxConnections)
	{
		// 添加到表头
		pContext->pNext = m_pConnectionList;
		m_pConnectionList = pContext;
		// 更新计数
		m_nCurrentConnection ++;

		::LeaveCriticalSection(&m_ConnectionListLock);
		return TRUE;
	}
	::LeaveCriticalSection(&m_ConnectionListLock);

	return FALSE;
}

void CIOCPServer::CloseAConnection(CIOCPContext *pContext)
{
	// 首先从列表中移除要关闭的连接
	::EnterCriticalSection(&m_ConnectionListLock);

	CIOCPContext* pTest = m_pConnectionList;
	if(pTest == pContext)
	{
		m_pConnectionList =  pTest->pNext; // [2009.8.9 mod Lostyears][old: m_pConnectionList =  pContext->pNext]
		m_nCurrentConnection --;
	}
	else
	{
		while(pTest != NULL && pTest->pNext !=  pContext)
			pTest = pTest->pNext;
		if(pTest != NULL)
		{
			pTest->pNext =  pContext->pNext;
			m_nCurrentConnection --;
		}
	}
	
	::LeaveCriticalSection(&m_ConnectionListLock);

	// 然后关闭客户套节字
	::EnterCriticalSection(&pContext->Lock);

	if(pContext->s != INVALID_SOCKET)
	{
		::closesocket(pContext->s);	
		pContext->s = INVALID_SOCKET;
	}
	pContext->bClosing = TRUE;

	::LeaveCriticalSection(&pContext->Lock);
}

void CIOCPServer::CloseAllConnections()
{
	// 遍历整个连接列表,关闭所有的客户套节字

	::EnterCriticalSection(&m_ConnectionListLock);

	CIOCPContext *pContext = m_pConnectionList;
	while(pContext != NULL)
	{	
		::EnterCriticalSection(&pContext->Lock);

		if(pContext->s != INVALID_SOCKET)
		{
			::closesocket(pContext->s);
			pContext->s = INVALID_SOCKET;
		}

		pContext->bClosing = TRUE;

		::LeaveCriticalSection(&pContext->Lock);	
		
		pContext = pContext->pNext;
	}

	m_pConnectionList = NULL;
	m_nCurrentConnection = 0;

	::LeaveCriticalSection(&m_ConnectionListLock);
}


BOOL CIOCPServer::InsertPendingAccept(CIOCPBuffer *pBuffer)
{
	// 将一个I/O缓冲区对象插入到m_pPendingAccepts表中

	::EnterCriticalSection(&m_PendingAcceptsLock);

	if(m_pPendingAccepts == NULL)
		m_pPendingAccepts = pBuffer;
	else
	{
		pBuffer->pNext = m_pPendingAccepts;
		m_pPendingAccepts = pBuffer;
	}
	m_nPendingAcceptCount ++;

	::LeaveCriticalSection(&m_PendingAcceptsLock);

	return TRUE;
}

BOOL CIOCPServer::RemovePendingAccept(CIOCPBuffer *pBuffer)
{
	BOOL bResult = FALSE;

	// 遍历m_pPendingAccepts表,从中移除pBuffer所指向的缓冲区对象
	::EnterCriticalSection(&m_PendingAcceptsLock);

	CIOCPBuffer *pTest = m_pPendingAccepts;
	if(pTest == pBuffer)	// 如果是表头元素
	{
		m_pPendingAccepts = pTest->pNext; // [2009.8.9 mod Lostyears][old: m_pPendingAccepts = pBuffer->pNext]
		bResult = TRUE;
	}
	else					// 不是表头元素的话,就要遍历这个表来查找了
	{
		while(pTest != NULL && pTest->pNext != pBuffer)
			pTest = pTest->pNext;
		if(pTest != NULL)
		{
			pTest->pNext = pBuffer->pNext;
			 bResult = TRUE;
		}
	}
	// 更新计数
	if(bResult)
		m_nPendingAcceptCount --;

	::LeaveCriticalSection(&m_PendingAcceptsLock);

	return  bResult;
}


CIOCPBuffer *CIOCPServer::GetNextReadBuffer(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{
	if(pBuffer != NULL)
	{
		// 如果与要读的下一个序列号相等,则读这块缓冲区
		if(pBuffer->nSequenceNumber == pContext->nCurrentReadSequence)
		{
			return pBuffer;
		}
		
		// 如果不相等,则说明没有按顺序接收数据,将这块缓冲区保存到连接的pOutOfOrderReads列表中

		// 列表中的缓冲区是按照其序列号从小到大的顺序排列的

		pBuffer->pNext = NULL;
		
		CIOCPBuffer *ptr = pContext->pOutOfOrderReads;
		CIOCPBuffer *pPre = NULL;
		while(ptr != NULL)
		{
			if(pBuffer->nSequenceNumber < ptr->nSequenceNumber)
				break;
			
			pPre = ptr;
			ptr = ptr->pNext;
		}
		
		if(pPre == NULL) // 应该插入到表头
		{
			pBuffer->pNext = pContext->pOutOfOrderReads;
			pContext->pOutOfOrderReads = pBuffer;
		}
		else			// 应该插入到表的中间
		{
			pBuffer->pNext = pPre->pNext;
			pPre->pNext = pBuffer; // [2009.8.9 mod Lostyears][old: pPre->pNext = pBuffer->pNext]
		}
	}

	// 检查表头元素的序列号,如果与要读的序列号一致,就将它从表中移除,返回给用户
	CIOCPBuffer *ptr = pContext->pOutOfOrderReads;
	if(ptr != NULL && (ptr->nSequenceNumber == pContext->nCurrentReadSequence))
	{
		pContext->pOutOfOrderReads = ptr->pNext;
		return ptr;
	}
	return NULL;
}


BOOL CIOCPServer::PostAccept(CIOCPBuffer *pBuffer)	// 在监听套节字上投递Accept请求
{
		// 设置I/O类型
		pBuffer->nOperation = OP_ACCEPT;

		// 投递此重叠I/O  
		DWORD dwBytes;
		pBuffer->sClient = ::WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
		BOOL b = m_lpfnAcceptEx(m_sListen, 
			pBuffer->sClient,
			pBuffer->buff, 
			pBuffer->nLen - ((sizeof(sockaddr_in) + 16) * 2), // [2010.5.16 bak Lostyears]如果这里为0, 表示不等待接收数据而通知, 如果这里改为0, 则GetAcceptExSockaddrs函数中的相应参数也得相应改
			sizeof(sockaddr_in) + 16, 
			sizeof(sockaddr_in) + 16, 
			&dwBytes, 
			&pBuffer->ol);
		if(!b && ::WSAGetLastError() != WSA_IO_PENDING)
		{
			return FALSE;
		}
		return TRUE;
}

BOOL CIOCPServer::PostRecv(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{
	// 设置I/O类型
	pBuffer->nOperation = OP_READ;	
	
	::EnterCriticalSection(&pContext->Lock);

	// 设置序列号
	pBuffer->nSequenceNumber = pContext->nReadSequence;

	// 投递此重叠I/O
	DWORD dwBytes;
	DWORD dwFlags = 0;
	WSABUF buf;
	buf.buf = pBuffer->buff;
	buf.len = pBuffer->nLen;
	if(::WSARecv(pContext->s, &buf, 1, &dwBytes, &dwFlags, &pBuffer->ol, NULL) != NO_ERROR)
	{
		if(::WSAGetLastError() != WSA_IO_PENDING)
		{
			::LeaveCriticalSection(&pContext->Lock);
			return FALSE;
		}
	}

	// 增加套节字上的重叠I/O计数和读序列号计数

	pContext->nOutstandingRecv ++;
	pContext->nReadSequence ++;

	::LeaveCriticalSection(&pContext->Lock);

	return TRUE;
}

BOOL CIOCPServer::PostSend(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{	
	// 跟踪投递的发送的数量,防止用户仅发送数据而不接收,导致服务器抛出大量发送操作
	if(pContext->nOutstandingSend > m_nMaxSends)
		return FALSE;

	// 设置I/O类型,增加套节字上的重叠I/O计数
	pBuffer->nOperation = OP_WRITE;

	// 投递此重叠I/O
	DWORD dwBytes;
	DWORD dwFlags = 0;
	WSABUF buf;
	buf.buf = pBuffer->buff;
	buf.len = pBuffer->nLen;
	if(::WSASend(pContext->s, 
			&buf, 1, &dwBytes, dwFlags, &pBuffer->ol, NULL) != NO_ERROR)
	{
		if(::WSAGetLastError() != WSA_IO_PENDING)
			return FALSE;
	}	
	
	// 增加套节字上的重叠I/O计数
	::EnterCriticalSection(&pContext->Lock);
	pContext->nOutstandingSend ++;
	::LeaveCriticalSection(&pContext->Lock);

	return TRUE;
}


BOOL CIOCPServer::Start(int nPort, int nMaxConnections, 
			int nMaxFreeBuffers, int nMaxFreeContexts, int nInitialReads)
{
	// 检查服务是否已经启动
	if(m_bServerStarted)
		return FALSE;

	// 保存用户参数
	m_nPort = nPort;
	m_nMaxConnections = nMaxConnections;
	m_nMaxFreeBuffers = nMaxFreeBuffers;
	m_nMaxFreeContexts = nMaxFreeContexts;
	m_nInitialReads = nInitialReads;

	// 初始化状态变量
	m_bShutDown = FALSE;
	m_bServerStarted = TRUE;


	// 创建监听套节字,绑定到本地端口,进入监听模式
	m_sListen = ::WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
	SOCKADDR_IN si;
	si.sin_family = AF_INET;
	si.sin_port = ::ntohs(m_nPort);
	si.sin_addr.S_un.S_addr = INADDR_ANY;
	if(::bind(m_sListen, (sockaddr*)&si, sizeof(si)) == SOCKET_ERROR)
	{
		m_bServerStarted = FALSE;
		return FALSE;
	}
	::listen(m_sListen, 200);

	// 创建完成端口对象
	m_hCompletion = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0);

	// 加载扩展函数AcceptEx
	GUID GuidAcceptEx = WSAID_ACCEPTEX;
	DWORD dwBytes;
	::WSAIoctl(m_sListen, 
		SIO_GET_EXTENSION_FUNCTION_POINTER, 
		&GuidAcceptEx, 
		sizeof(GuidAcceptEx),
		&m_lpfnAcceptEx, 
		sizeof(m_lpfnAcceptEx), 
		&dwBytes, 
		NULL, 
		NULL);
	
	// 加载扩展函数GetAcceptExSockaddrs
	GUID GuidGetAcceptExSockaddrs = WSAID_GETACCEPTEXSOCKADDRS;
	::WSAIoctl(m_sListen,
		SIO_GET_EXTENSION_FUNCTION_POINTER,
		&GuidGetAcceptExSockaddrs,
		sizeof(GuidGetAcceptExSockaddrs),
		&m_lpfnGetAcceptExSockaddrs,
		sizeof(m_lpfnGetAcceptExSockaddrs),
		&dwBytes,
		NULL,
		NULL
		);
	
	
	// 将监听套节字关联到完成端口,注意,这里为它传递的CompletionKey为0
	::CreateIoCompletionPort((HANDLE)m_sListen, m_hCompletion, (DWORD)0, 0);

	// 注册FD_ACCEPT事件。
	// 如果投递的AcceptEx I/O不够,线程会接收到FD_ACCEPT网络事件,说明应该投递更多的AcceptEx I/O
	WSAEventSelect(m_sListen, m_hAcceptEvent, FD_ACCEPT);

	// 创建监听线程
	m_hListenThread = ::CreateThread(NULL, 0, _ListenThreadProc, this, 0, NULL);
	
	return TRUE;
}

void CIOCPServer::Shutdown()
{
	if(!m_bServerStarted)
		return;

	// 通知监听线程,马上停止服务
	m_bShutDown = TRUE;
	::SetEvent(m_hAcceptEvent);
	// 等待监听线程退出
	::WaitForSingleObject(m_hListenThread, INFINITE);
	::CloseHandle(m_hListenThread);
	m_hListenThread = NULL;

	m_bServerStarted = FALSE;
}

DWORD WINAPI CIOCPServer::_ListenThreadProc(LPVOID lpParam)
{
	CIOCPServer *pThis = (CIOCPServer*)lpParam;

	// 先在监听套节字上投递几个Accept I/O
	CIOCPBuffer *pBuffer;
	for(int i=0; i<pThis->m_nInitialAccepts; i++)
	{
		pBuffer = pThis->AllocateBuffer(BUFFER_SIZE);
		if(pBuffer == NULL)
			return -1;
		pThis->InsertPendingAccept(pBuffer);
		pThis->PostAccept(pBuffer);
	}

	// 构建事件对象数组,以便在上面调用WSAWaitForMultipleEvents函数
	HANDLE hWaitEvents[2 + MAX_THREAD];
	int nEventCount = 0;
	hWaitEvents[nEventCount ++] = pThis->m_hAcceptEvent;
	hWaitEvents[nEventCount ++] = pThis->m_hRepostEvent;

	// 创建指定数量的工作线程在完成端口上处理I/O
	for(int i=0; i<MAX_THREAD; i++)
	{
		hWaitEvents[nEventCount ++] = ::CreateThread(NULL, 0, _WorkerThreadProc, pThis, 0, NULL);
	}

	// 下面进入无限循环,处理事件对象数组中的事件
	while(TRUE)
	{
		int nIndex = ::WSAWaitForMultipleEvents(nEventCount, hWaitEvents, FALSE, 60*1000, FALSE);
	
		// 首先检查是否要停止服务
		if(pThis->m_bShutDown || nIndex == WSA_WAIT_FAILED)
		{
			// 关闭所有连接
			pThis->CloseAllConnections();
			::Sleep(0);		// 给I/O工作线程一个执行的机会
			// 关闭监听套节字
			::closesocket(pThis->m_sListen);
			pThis->m_sListen = INVALID_SOCKET;
			::Sleep(0);		// 给I/O工作线程一个执行的机会

			// 通知所有I/O处理线程退出
			for(int i=2; i<MAX_THREAD + 2; i++)
			{	
				::PostQueuedCompletionStatus(pThis->m_hCompletion, -1, 0, NULL);
			}

			// 等待I/O处理线程退出
			::WaitForMultipleObjects(MAX_THREAD, &hWaitEvents[2], TRUE, 5*1000);

			for(int i=2; i<MAX_THREAD + 2; i++)
			{	
				::CloseHandle(hWaitEvents[i]);
			}
		
			::CloseHandle(pThis->m_hCompletion);

			pThis->FreeBuffers();
			pThis->FreeContexts();
			::ExitThread(0);
		}	

		// 1)定时检查所有未返回的AcceptEx I/O的连接建立了多长时间
		if(nIndex == WSA_WAIT_TIMEOUT)
		{
			pBuffer = pThis->m_pPendingAccepts;
			while(pBuffer != NULL)
			{
				int nSeconds;
				int nLen = sizeof(nSeconds);
				// 取得连接建立的时间
				::getsockopt(pBuffer->sClient, 
					SOL_SOCKET, SO_CONNECT_TIME, (char *)&nSeconds, &nLen);	
				// 如果超过2分钟客户还不发送初始数据,就让这个客户go away
				if(nSeconds != -1 && nSeconds > 2*60)
				{   
					closesocket(pBuffer->sClient);
                    pBuffer->sClient = INVALID_SOCKET;
				}

				pBuffer = pBuffer->pNext;
			}
		}
		else
		{
			nIndex = nIndex - WAIT_OBJECT_0;
			WSANETWORKEVENTS ne;
            int nLimit=0;
			if(nIndex == 0)			// 2)m_hAcceptEvent事件对象受信,说明投递的Accept请求不够,需要增加
			{
				::WSAEnumNetworkEvents(pThis->m_sListen, hWaitEvents[nIndex], &ne);
				if(ne.lNetworkEvents & FD_ACCEPT)
				{
					nLimit = 50;  // 增加的个数,这里设为50个
				}
			}
			else if(nIndex == 1)	// 3)m_hRepostEvent事件对象受信,说明处理I/O的线程接受到新的客户
			{
				nLimit = InterlockedExchange(&pThis->m_nRepostCount, 0);
			}
			else if(nIndex > 1)		// I/O服务线程退出,说明有错误发生,关闭服务器
			{
				pThis->m_bShutDown = TRUE;
				continue;
			}

			// 投递nLimit个AcceptEx I/O请求
			int i = 0;
			while(i++ < nLimit && pThis->m_nPendingAcceptCount < pThis->m_nMaxAccepts)
			{
				pBuffer = pThis->AllocateBuffer(BUFFER_SIZE);
				if(pBuffer != NULL)
				{
					pThis->InsertPendingAccept(pBuffer);
					pThis->PostAccept(pBuffer);
				}
			}
		}
	}
	return 0;
}

DWORD WINAPI CIOCPServer::_WorkerThreadProc(LPVOID lpParam)
{
#ifdef _DEBUG
			::OutputDebugString("	WorkerThread 启动... 
");
#endif // _DEBUG

	CIOCPServer *pThis = (CIOCPServer*)lpParam;

	CIOCPBuffer *pBuffer;
	DWORD dwKey;
	DWORD dwTrans;
	LPOVERLAPPED lpol;
	while(TRUE)
	{
		// 在关联到此完成端口的所有套节字上等待I/O完成
		BOOL bOK = ::GetQueuedCompletionStatus(pThis->m_hCompletion, 
					&dwTrans, (LPDWORD)&dwKey, (LPOVERLAPPED*)&lpol, WSA_INFINITE);

		if(dwTrans == -1) // 用户通知退出
		{
#ifdef _DEBUG
			::OutputDebugString("	WorkerThread 退出 
");
#endif // _DEBUG
			::ExitThread(0);
		}


		pBuffer = CONTAINING_RECORD(lpol, CIOCPBuffer, ol); // [2009.8.9 bak Lostyears][lpol作为CIOCPBuffer的ol成员,由其地址取CIOCPBuffer实例首地址]
		int nError = NO_ERROR;
		if(!bOK)						// 在此套节字上有错误发生
		{
			SOCKET s;
			if(pBuffer->nOperation == OP_ACCEPT)
			{
				s = pThis->m_sListen;
			}
			else
			{
				if(dwKey == 0)
					break;
				s = ((CIOCPContext*)dwKey)->s;
			}
			DWORD dwFlags = 0;
			if(!::WSAGetOverlappedResult(s, &pBuffer->ol, &dwTrans, FALSE, &dwFlags))
			{
				nError = ::WSAGetLastError();
			}
		}
		pThis->HandleIO(dwKey, pBuffer, dwTrans, nError);
	}

#ifdef _DEBUG
			::OutputDebugString("	WorkerThread 退出 
");
#endif // _DEBUG
	return 0;
}


void CIOCPServer::HandleIO(DWORD dwKey, CIOCPBuffer *pBuffer, DWORD dwTrans, int nError)
{
	CIOCPContext *pContext = (CIOCPContext *)dwKey;

#ifdef _DEBUG
			::OutputDebugString("	HandleIO... 
");
#endif // _DEBUG
	
	// 1)首先减少套节字上的未决I/O计数
	if(pContext != NULL)
	{
		::EnterCriticalSection(&pContext->Lock);
		
		if(pBuffer->nOperation == OP_READ)
			pContext->nOutstandingRecv --;
		else if(pBuffer->nOperation == OP_WRITE)
			pContext->nOutstandingSend --;
		
		::LeaveCriticalSection(&pContext->Lock);
		
		// 2)检查套节字是否已经被我们关闭 [2009.8.9 bak Lostyears][如果关闭则释放剩下的未决IO]
		if(pContext->bClosing) 
		{
#ifdef _DEBUG
			::OutputDebugString("	检查到套节字已经被我们关闭 
");
#endif // _DEBUG
			if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)
			{		
				ReleaseContext(pContext);
			}
			// 释放已关闭套节字的未决I/O
			ReleaseBuffer(pBuffer);	
			return;
		}
	}
	else
	{
		RemovePendingAccept(pBuffer); // [2009.8.9 bak Lostyears][sListen关联了iocp, 关联时dwKey为0, 所以当有新连接发送数据时会执行到此]
	}

	// 3)检查套节字上发生的错误,如果有的话,通知用户,然后关闭套节字
	if(nError != NO_ERROR)
	{
		if(pBuffer->nOperation != OP_ACCEPT)
		{
			NotifyConnectionError(pContext, pBuffer, nError);
			CloseAConnection(pContext);
			if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)
			{		
				ReleaseContext(pContext);
			}
#ifdef _DEBUG
			::OutputDebugString("	检查到客户套节字上发生错误 
");
#endif // _DEBUG
		}
		else // 在监听套节字上发生错误,也就是监听套节字处理的客户出错了
		{
			// 客户端出错,释放I/O缓冲区
			if(pBuffer->sClient != INVALID_SOCKET)
			{
				::closesocket(pBuffer->sClient);
				pBuffer->sClient = INVALID_SOCKET;
			}
#ifdef _DEBUG
			::OutputDebugString("	检查到监听套节字上发生错误 
");
#endif // _DEBUG
		}

		ReleaseBuffer(pBuffer);
		return;
	}


	// 开始处理
	if(pBuffer->nOperation == OP_ACCEPT)
	{
		if(dwTrans == 0) // [2010.5.16 bak Lostyears]如果AcceptEx的数据接收缓冲区设为0, 一连接上就会执行到这
		{
#ifdef _DEBUG
			::OutputDebugString("	监听套节字上客户端关闭 
");
#endif // _DEBUG
			
			if(pBuffer->sClient != INVALID_SOCKET)
			{
				::closesocket(pBuffer->sClient);
				pBuffer->sClient = INVALID_SOCKET;
			}
		}
		else
		{
			// 为新接受的连接申请客户上下文对象
		CIOCPContext *pClient = AllocateContext(pBuffer->sClient);
			if(pClient != NULL)
			{
				if(AddAConnection(pClient))
				{	
					// 取得客户地址
					int nLocalLen, nRmoteLen;
					LPSOCKADDR pLocalAddr, pRemoteAddr;
					m_lpfnGetAcceptExSockaddrs(
						pBuffer->buff,
						pBuffer->nLen - ((sizeof(sockaddr_in) + 16) * 2), // [2010.5.16 bak Lostyears]和AcceptEx相应参数对应
						sizeof(sockaddr_in) + 16,
						sizeof(sockaddr_in) + 16,
						(SOCKADDR **)&pLocalAddr,
						&nLocalLen,
						(SOCKADDR **)&pRemoteAddr,
						&nRmoteLen);
					memcpy(&pClient->addrLocal, pLocalAddr, nLocalLen);
					memcpy(&pClient->addrRemote, pRemoteAddr, nRmoteLen);

					// [2010.1.15 add Lostyears][加入KeepAlive机制]
					BOOL bKeepAlive = TRUE;
					int nRet = ::setsockopt(pClient->s, SOL_SOCKET, SO_KEEPALIVE, (char*)&bKeepAlive, sizeof(bKeepAlive));
					if (nRet == SOCKET_ERROR)
					{
						CloseAConnection(pClient);
					}
					else
					{
						// 设置KeepAlive参数
						tcp_keepalive alive_in	= {0};
						tcp_keepalive alive_out	= {0};
						alive_in.keepalivetime		= 5000;	// 开始首次KeepAlive探测前的TCP空闲时间
						alive_in.keepaliveinterval	= 1000;	// 两次KeepAlive探测间的时间间隔
						alive_in.onoff	= TRUE;
						unsigned long ulBytesReturn	= 0;
						nRet = ::WSAIoctl(pClient->s, SIO_KEEPALIVE_VALS, &alive_in, sizeof(alive_in),
							&alive_out, sizeof(alive_out), &ulBytesReturn, NULL, NULL);
						if (nRet == SOCKET_ERROR)
						{
							CloseAConnection(pClient);
						}
						else
						{
							// 关联新连接到完成端口对象
							::CreateIoCompletionPort((HANDLE)pClient->s, m_hCompletion, (DWORD)pClient, 2);
							
							// 通知用户
							pBuffer->nLen = dwTrans;
							OnConnectionEstablished(pClient, pBuffer);
							
							// 向新连接投递几个Read请求,这些空间在套节字关闭或出错时释放
							for(int i=0; i<m_nInitialReads; i++) // [2009.8.21 mod Lostyears][将常量值改为m_nInitialReads]
							{
								CIOCPBuffer *p = AllocateBuffer(BUFFER_SIZE);
								if(p != NULL)
								{
									if(!PostRecv(pClient, p))
									{
										CloseAConnection(pClient);
										break;
									}
								}
							}
						}
					}
					
 					//// 关联新连接到完成端口对象
 					//::CreateIoCompletionPort((HANDLE)pClient->s, m_hCompletion, (DWORD)pClient, 0);
 					//
 					//// 通知用户
 					//pBuffer->nLen = dwTrans;
 					//OnConnectionEstablished(pClient, pBuffer);
 					//
 					//// 向新连接投递几个Read请求,这些空间在套节字关闭或出错时释放
 					//for(int i=0; i<m_nInitialReads; i++) // [2009.8.22 mod Lostyears][old: i<5]
 					//{
 					//	CIOCPBuffer *p = AllocateBuffer(BUFFER_SIZE);
 					//	if(p != NULL)
 					//	{
 					//		if(!PostRecv(pClient, p))
 					//		{
 					//			CloseAConnection(pClient);
 					//			break;
 					//		}
 					//	}
 					//}
				}
				else	// 连接数量已满,关闭连接
				{
					CloseAConnection(pClient);
					ReleaseContext(pClient);
				}
			}
			else
			{
				// 资源不足,关闭与客户的连接即可
				::closesocket(pBuffer->sClient);
				pBuffer->sClient = INVALID_SOCKET;
			}
		}
		
		// Accept请求完成,释放I/O缓冲区
		ReleaseBuffer(pBuffer);	

		// 通知监听线程继续再投递一个Accept请求
		::InterlockedIncrement(&m_nRepostCount);
		::SetEvent(m_hRepostEvent);
	}
	else if(pBuffer->nOperation == OP_READ)
	{
		if(dwTrans == 0)	// 对方关闭套节字
		{
			// 先通知用户
			pBuffer->nLen = 0;
			NotifyConnectionClosing(pContext, pBuffer);	

			// 再关闭连接
			CloseAConnection(pContext);
			// 释放客户上下文和缓冲区对象
			if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)
			{		
				ReleaseContext(pContext);
			}
			ReleaseBuffer(pBuffer);	
		}
		else
		{
			pBuffer->nLen = dwTrans;
			// 按照I/O投递的顺序读取接收到的数据
			CIOCPBuffer *p = GetNextReadBuffer(pContext, pBuffer);
			while(p != NULL)
			{
				// 通知用户
				OnReadCompleted(pContext, p);
				// 增加要读的序列号的值
				::InterlockedIncrement((LONG*)&pContext->nCurrentReadSequence);
				// 释放这个已完成的I/O
				ReleaseBuffer(p);
				p = GetNextReadBuffer(pContext, NULL);
			}

			// 继续投递一个新的接收请求
			pBuffer = AllocateBuffer(BUFFER_SIZE);
			if(pBuffer == NULL || !PostRecv(pContext, pBuffer))
			{
				CloseAConnection(pContext);
			}
		}
	}
	else if(pBuffer->nOperation == OP_WRITE)
	{

		if(dwTrans == 0)	// 对方关闭套节字
		{
			// 先通知用户
			pBuffer->nLen = 0;
			NotifyConnectionClosing(pContext, pBuffer);	

			// 再关闭连接
			CloseAConnection(pContext);

			// 释放客户上下文和缓冲区对象
			if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0)
			{		
				ReleaseContext(pContext);
			}
			ReleaseBuffer(pBuffer);	
		}
		else
		{
			// 写操作完成,通知用户
			pBuffer->nLen = dwTrans;
			OnWriteCompleted(pContext, pBuffer);
			// 释放SendText函数申请的缓冲区
			ReleaseBuffer(pBuffer);
		}
	}
}

// 当套件字关闭或出错时通知
void CIOCPServer::NotifyConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{
	::EnterCriticalSection(&m_CloseOrErrLock);
	if (!pContext->bNotifyCloseOrError)
	{
		pContext->bNotifyCloseOrError = true;
		OnConnectionClosing(pContext, pBuffer);
	}
	::LeaveCriticalSection(&m_CloseOrErrLock);
}

void CIOCPServer::NotifyConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError)
{
	::EnterCriticalSection(&m_CloseOrErrLock);
	if (!pContext->bNotifyCloseOrError)
	{
		pContext->bNotifyCloseOrError = true;
		OnConnectionError(pContext, pBuffer, nError);
	}
	::LeaveCriticalSection(&m_CloseOrErrLock);
}



BOOL CIOCPServer::SendText(CIOCPContext *pContext, char *pszText, int nLen)
{
	CIOCPBuffer *pBuffer = AllocateBuffer(nLen);
	if(pBuffer != NULL)
	{
		memcpy(pBuffer->buff, pszText, nLen);
		return PostSend(pContext, pBuffer);
	}
	return FALSE;
}


void CIOCPServer::OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{
}

void CIOCPServer::OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{
}


void CIOCPServer::OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{
}

void CIOCPServer::OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
{
}

void CIOCPServer::OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError)
{
}
////////////////////////////////////////////////
// iocpserver.cpp文件


// CIOCPServer类的测试程序

#include "iocp.h"
#include <stdio.h>
#include <windows.h>

class CMyServer : public CIOCPServer
{
public:

	void OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
	{
		printf("接收到一个新的连接(%d): %s
", 
					GetCurrentConnection(), ::inet_ntoa(pContext->addrRemote.sin_addr));
		printf("接受到一个数据包, 其大小为: %d字节
", pBuffer->nLen);

		SendText(pContext, pBuffer->buff, pBuffer->nLen);
	}

	void OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
	{
		printf("一个连接关闭
");
	}

	void OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError)
	{
		printf("一个连接发生错误: %d
", nError);
	}

	void OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
	{
		printf("接受到一个数据包, 其大小为: %d字节
", pBuffer->nLen);
		SendText(pContext, pBuffer->buff, pBuffer->nLen);
	}
	
	void OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer)
	{
		printf("一个数据包发送成功, 其大小为: %d字节
 ", pBuffer->nLen);
	}
};

void main()
{
	CMyServer *pServer = new CMyServer;

	// 开启服务
	if(pServer->Start())
	{
		printf("服务器开启成功...
");
	}
	else
	{
		printf("服务器开启失败!
");
		return;
	}

	// 创建事件对象,让ServerShutdown程序能够关闭自己
	HANDLE hEvent = ::CreateEvent(NULL, FALSE, FALSE, "ShutdownEvent");
	::WaitForSingleObject(hEvent, INFINITE);
	::CloseHandle(hEvent);

	// 关闭服务
	pServer->Shutdown();
	delete pServer;

	printf("服务器关闭
 ");

}


参考:

《Windows网络与通信程序设计》 王艳平 张越

转载请注明!

原文地址:https://www.cnblogs.com/dps001/p/4383319.html