18,356
社区成员
发帖
与我相关
我的任务
分享
//监听线程
DWORD WINAPI CService::ClientListen(void* p)
{
while(TRUE)
{
SOCKET clientSocket=::accept(m_pInstance->m_hServiceSocket,NULL,NULL);
if(clientSocket==SOCKET_ERROR)
continue;
::CreateIoCompletionPort((HANDLE)clientSocket,m_pInstance->m_hServiceIocp,0,0);
LPIOCONTEXT pIoContext=(LPIOCONTEXT)GlobalAlloc(GPTR, sizeof( IOCONTEXT));
pIoContext->wsaBuffer.buf=pIoContext->pWorkBuffer;
pIoContext->wsaBuffer.len=10;
//下面的代码会引发非常诡异的问题,后面会讲到
UINT nRetVal =::WSARecv((SOCKET)clientSocket,&(pIoContext->wsaBuffer),1,&(pIoContext->dwIoSize),&(pIoContext->dwlFlags),&(pIoContext->overlapped), NULL);/*关键位置A*/
}
return 0;
}
//完成处理线程
DWORD WINAPI CService::DoService(void* p)
{
DWORD dwBytesXfered=0;
DWORD dwKey=0;
LPIOCONTEXT pIoContext=NULL;
while(TRUE)
{
GetQueuedCompletionStatus(m_pInstance->m_ServiceIocp,&dwBytesXfered,&dwKey,(LPOVERLAPPED*)(&pIoContext),INFINITE);
GlobalFree(pIoContext);/*位置B*/
}
return 0;
}
BOOL CClient::Recv()
{
DWORD flags=0;
DWORD recvBytes=0;
ZeroMemory(&m_IO,sizeof(IO_OPERATION_DATA));
m_IO.type=READ;
if(WSARecv(m_s,&m_IO.dataBuf,1,&recvBytes,&flags,&m_IO.overlapped,NULL)==SOCKET_ERROR)
{
if(ERROR_IO_PENDING!=WSAGetLastError())
{
return FALSE;
}
}
return TRUE;
}