完成端口(IOCP)的实现(5)

发布时间:2021-06-06

整理的一个简单的完成端口类

on);
DeleteCriticalSection(&m_conSection);
DeleteCriticalSection(&m_ioMenListSection);
DeleteCriticalSection(&m_hdMemListSection);
}

//启动完成端口服务
bool NetCompletionPort::StartServer(int port)
{
WSADATA m_wsaData;
m_port = port;

if(WSAStartup(MAKEWORD(2,2), &m_wsaData))
return FALSE;

if(InitWinSock() && InitListenSocket() && InitListenEvent() && InitWorkThread())
{
m_isCreate = TRUE;
m_pThreadAccept->Start(); //启动accept线程
std::vector<WorkThread*>::iterator pos = m_pWorkThreadList->begin();
while (pos != m_pWorkThreadList->end())
{
(*pos)->Start(); //启动工作者线程
pos++;
}
}
else
{
StopServer();
return FALSE;
}

return TRUE;
}

//初始化完成端口,创建工作者线程
bool NetCompletionPort::InitWinSock()
{
m_comPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,0,0);

if(!m_comPort)
return FALSE;

SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);

for(int i=0;i<(sysInfo.dwNumberOfProcessors*2);i++)
{
WorkThread* pThread = new WorkThread(&WorkThreadFun,this);
if(pThread->Init())
m_pWorkThreadList->push_back(pThread);
else
{
delete pThread;
return FALSE;
}
}
return TRUE;
}

//创建监听端口,并关联完成端口,启动监听
bool NetCompletionPort::InitListenSocket()
{
m_listenSocket = WSASocket(PF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED); //创建监听服务端口

if(INVALID_SOCKET == m_listenSocket)
{
m_listenSocket = NULL;
return FALSE;
}

if(!CreateIoCompletionPort((HANDLE)m_listenSocket,m_comPort,0,0)) //关联完成端口
return FALSE;
SOCKADDR_IN SockAddr;
SockAddr.sin_family = AF_INET;
SockAddr.sin_port = htons(m_port);
SockAddr.sin_addr.s_addr = INADDR_ANY;

if(SOCKET_ERROR == bind(m_listenSocket,(PSOCKADDR)&SockAddr,sizeof(SockAddr))) //绑定
return FALSE;

if(SOCKET_ERROR == listen(m_listenSocket,10)) //监听
return FALSE;

DWORD dwTemp=0;

if(SOCKET_ERROR == WSAIoctl(m_listenSocket,SIO_GET_EXTENSION_FUNCTION_POINTER, //获取扩展函数调用
&g_GUIDAccep
tEx,sizeof(g_GUIDAcceptEx),&m_pAcceptEx,sizeof(m_pAcceptEx),
&dwTemp,NULL,NULL))
{
m_pAcceptEx = NULL;
return FALSE;
}

完成端口(IOCP)的实现(5).doc 将本文的Word文档下载到电脑

精彩图片

热门精选

大家正在看

× 游客快捷下载通道(下载后可以自由复制和排版)

限时特价:7 元/份 原价:20元

支付方式:

开通VIP包月会员 特价:29元/月

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:fanwen365 QQ:370150219