完成端口(IOCP)的实现(8)
发布时间:2021-06-06
发布时间:2021-06-06
整理的一个简单的完成端口类
}
LeaveCriticalSection(&m_ioMenListSection);
memset(pData,0,sizeof(PER_IO_CONTEXT));
return pData;
}
//获取一个句柄资源
LPPER_HANDLE_CONTEXT NetCompletionPort::GetHandleMem()
{
LPPER_HANDLE_CONTEXT pData = NULL;
EnterCriticalSection(&m_hdMemListSection);
if(m_pHandleMemList->size() > 0)
{
pData = m_pHandleMemList->front();
m_pHandleMemList->pop_front();
}
else
{
pData = (LPPER_HANDLE_CONTEXT)malloc(sizeof(PER_HANDLE_CONTEXT));
}
LeaveCriticalSection(&m_hdMemListSection);
memset(pData,0,sizeof(PER_HANDLE_CONTEXT));
return pData;
}
//归还一个IO资源
void NetCompletionPort::InsertIoMem(LPPER_IO_CONTEXT pMem)
{
EnterCriticalSection(&m_ioMenListSection);
if(m_pIoMemList->size() < MAX_MEM_COUNT)
m_pIoMemList->push_back(pMem);
else
free(pMem);
LeaveCriticalSection(&m_ioMenListSection);
}
//归还一个句柄资源
void NetCompletionPort::InsertHandleMem(LPPER_HANDLE_CONTEXT pMem)
{
EnterCriticalSection(&m_hdMemListSection);
if(m_pHandleMemList->size() < MAX_MEM_COUNT)
m_pHandleMemList->push_back(pMem);
else
free(pMem);
LeaveCriticalSection(&m_hdMemListSection);
}
//发起多个access监听
bool NetCompletionPort::PostAcceptEx()
{
for(int i=0; i<10; i++)
{
SOCKET socketAcp = WSASocket(PF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED);
if(INVALID_SOCKET == socketAcp)
return FALSE;
LPPER_IO_CONTEXT temp = GetIoMem(); //申请一个IO资源
temp->IoOperation = IO_ACCEPT;
temp->sClient = socketAcp;
temp->id = socketAcp;
temp->wsabuf.len = MAX_BUF;
DWORD dwByte;
if( !m_pAcceptEx(m_listenSocket, socketAcp, temp->buf, MAX_BUF-((sizeof(SOCKADDR_IN)+16)*2),
sizeof(SOCKADDR_IN)+16, sizeof(SOCKADDR_IN)+16, &dwByte, &temp->ol) )
{
if(ERROR_IO_PENDING != WSAGetLastError())
{
::closesocket(socketAcp);
InsertIoMem(temp);
return FALSE;
}
}
}
return TRUE;
}
//释放某客户端连接
bool NetCompletionPort::Disconnect(int socket)
{
bool rlt = FALSE;
EnterCriticalSection(&m_clientListSection);
std::map<int,NetClient*>::iterator pos = m_pClientList->find(socket);
if(pos != m_pClientList->end())
{
NetClient* pClient = pos->second;
pClient->Disconnect();
//断开连接
InsertHandleMem(pClient->m_pComKey); //归还句柄资源
delete pClient;
m_pClientList->erase(socket); //从链表中清除
上一篇:一年级上册语文生字自测练习组词