刚开始想学习IOCP(后面也会叫完成端口)的时候,在网上找到的最多的是小猪的IOCP资源,里面用的AcceptEx+IOCP来实现的,把代码下载下来看了半天都没看明白,然后想如果从最简单的阻塞模式入手,会不会更容易理解IOCP的运用呢?所以就花了了几天时间自己写了一个,总算大概弄懂了IOCP在socket里面的用法了,具体流程如下:
1.网络库的初始化+IOCP初始化和线程的创建+服务端socket的初始化
a.网络库的初始化
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
WSADATA wsa;
int nErr = WSAStartup(MAKEWORD(2, 2), &wsa);
if(nErr != 0)
{
nErr = GetLastError();
std::cout<<"WSAStartup error, num ="<<nErr<<std::endl;
return -1;
}
if(HIBYTE(wsa.wVersion) != 2 || LOBYTE(wsa.wVersion) != 2)
{
return -1;
}
b.IOCP初始化和线程的创建
completion_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);//创建完成端口 if(completion_port == NULL) { nErr = GetLastError(); std::cout<<"CreateIoCompletionPort err, number="<<nErr<<std::endl; return -1; } SYSTEM_INFO sys_info; GetSystemInfo(&sys_info); int thread_cnt = sys_info.dwNumberOfProcessors * 2 - 1; HANDLE* pthread_handle = new HANDLE[thread_cnt]; DWORD* pthread_id = new DWORD[thread_cnt]; for(int index = 0; index < thread_cnt; ++index) //创建处理完成端口上的I/0事件的线程 { pthread_handle[index] = CreateThread(NULL, 0, ThreadFunc, completion_port, NULL, &pthread_id[index]); }
c.服务端socket的初始化
SOCKET soct = socket(AF_INET, SOCK_STREAM, 0); if(soct == INVALID_SOCKET) { nErr = GetLastError(); std::cout<<"socket err, number="<<nE