c++ iocp 服务端程序例子
时间: 2024-01-12 19:04:19 浏览: 153
以下是一个使用IOCP实现的简单服务端程序的示例代码:
```
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
#define BUFFER_SIZE 1024
#define MAX_CLIENTS 10
struct ClientContext {
SOCKET socket;
char buffer[BUFFER_SIZE];
int bytesReceived;
OVERLAPPED overlapped;
};
int main() {
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
// 创建监听socket
SOCKET listenSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
SOCKADDR_IN serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(12345);
bind(listenSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
listen(listenSocket, SOMAXCONN);
// 创建IOCP
HANDLE iocpHandle = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
// 将监听socket加入IOCP
CreateIoCompletionPort((HANDLE)listenSocket, iocpHandle, (ULONG_PTR)listenSocket, 0);
// 创建客户端上下文数组
ClientContext clientContexts[MAX_CLIENTS];
for (int i = 0; i < MAX_CLIENTS; i++) {
clientContexts[i].socket = INVALID_SOCKET;
clientContexts[i].bytesReceived = 0;
ZeroMemory(&clientContexts[i].overlapped, sizeof(OVERLAPPED));
}
// 不断等待客户端连接
while (true) {
// 接收客户端连接请求
SOCKET clientSocket = accept(listenSocket, NULL, NULL);
// 将客户端socket加入IOCP
CreateIoCompletionPort((HANDLE)clientSocket, iocpHandle, (ULONG_PTR)clientSocket, 0);
// 找到一个空闲的客户端上下文
ClientContext* clientContext = NULL;
for (int i = 0; i < MAX_CLIENTS; i++) {
if (clientContexts[i].socket == INVALID_SOCKET) {
clientContext = &clientContexts[i];
break;
}
}
if (clientContext == NULL) {
std::cout << "Too many clients." << std::endl;
closesocket(clientSocket);
continue;
}
// 初始化客户端上下文
clientContext->socket = clientSocket;
clientContext->bytesReceived = 0;
ZeroMemory(&clientContext->overlapped, sizeof(OVERLAPPED));
// 异步接收数据
DWORD flags = 0;
WSARecv(clientSocket, &clientContext->buffer[clientContext->bytesReceived], BUFFER_SIZE - clientContext->bytesReceived, NULL, &flags, &clientContext->overlapped, NULL);
}
// 关闭监听socket
closesocket(listenSocket);
// 关闭IOCP
CloseHandle(iocpHandle);
WSACleanup();
return 0;
}
```
该程序使用IOCP监听客户端连接请求,并异步接收客户端发送的数据。程序中使用了一个客户端上下文数组来保存每个客户端的状态信息。在接收到客户端连接请求时,程序会找到一个空闲的客户端上下文,并将连接的客户端socket加入IOCP。在异步接收数据时,程序使用客户端上下文中的缓冲区来保存已接收到的数据,并在数据接收完成后再次调用WSARecv函数来继续接收数据。程序中使用了OVERLAPPED结构体来实现异步操作。程序使用了WSARecv函数来异步接收数据。
阅读全文