要使用IOCP(I/O Completion Ports)來實現C++中的Socket通信,可以按照以下步驟進行操作:
HANDLE hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
bind(sock, (SOCKADDR*)&addr, sizeof(addr));
CreateIoCompletionPort((HANDLE)sock, hIOCP, (ULONG_PTR)sock, 0);
WSABUF wsaBuf;
wsaBuf.buf = // 緩沖區指針
wsaBuf.len = // 緩沖區長度
DWORD bytesTransferred = 0;
DWORD flags = 0;
OVERLAPPED* pOverlapped = nullptr;
WSARecv(sock, &wsaBuf, 1, &bytesTransferred, &flags, pOverlapped, nullptr);
DWORD WINAPI WorkerThread(LPVOID lpParam) {
while (true) {
DWORD bytesTransferred = 0;
ULONG_PTR completionKey = 0;
LPOVERLAPPED lpOverlapped = nullptr;
GetQueuedCompletionStatus(hIOCP, &bytesTransferred, &completionKey, &lpOverlapped, INFINITE);
// 處理接收到的數據
// 重新投遞接收請求
WSARecv(sock, &wsaBuf, 1, &bytesTransferred, &flags, pOverlapped, nullptr);
}
return 0;
}
for (int i = 0; i < numThreads; ++i) {
HANDLE hThread = CreateThread(NULL, 0, WorkerThread, NULL, 0, NULL);
CloseHandle(hThread);
}
通過以上步驟,就可以使用IOCP來進行Socket通信了。注意,這只是一個基本示例,實際使用時可能需要根據具體需求進行調整和擴展。