IOCP模型c++代码
时间: 2023-03-22 21:01:27 浏览: 380
windows IOCP示例代码
IOCP是一种高效的I/O多路复用模型,适用于Windows系统上的网络编程。下面是一个简单的使用IOCP模型的C代码示例,实现了一个简单的回显服务器:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#define BUFSIZE 1024
typedef struct _PER_HANDLE_DATA {
SOCKET Socket;
SOCKADDR_STORAGE ClientAddr;
} PER_HANDLE_DATA, *LPPER_HANDLE_DATA;
typedef struct _PER_IO_DATA {
OVERLAPPED Overlapped;
WSABUF DataBuf;
char Buffer[BUFSIZE];
int OperationType;
} PER_IO_DATA, *LPPER_IO_DATA;
DWORD WINAPI WorkerThread(LPVOID lpParam);
int main(int argc, char* argv[]) {
WSADATA wsaData;
SOCKET ListenSocket, AcceptSocket;
SOCKADDR_STORAGE LocalAddr, ClientAddr;
DWORD Flags;
LPPER_HANDLE_DATA PerHandleData;
LPPER_IO_DATA PerIoData;
DWORD RecvBytes, SendBytes;
DWORD BytesTransferred;
DWORD ThreadId;
HANDLE CompletionPort, ThreadHandle;
int i;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("WSAStartup failed with error: %d\n", WSAGetLastError());
return 1;
}
// 创建完成端口
CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (CompletionPort == NULL) {
printf("CreateIoCompletionPort failed with error: %d\n", GetLastError());
return 1;
}
// 创建监听套接字
ListenSocket = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %d\n", WSAGetLastError());
return 1;
}
// 绑定地址并监听
memset(&LocalAddr, 0, sizeof(LocalAddr));
LocalAddr.ss_family = AF_INET6;
((SOCKADDR_IN6*)&LocalAddr)->sin6_port = htons(12345);
((SOCKADDR_IN6*)&LocalAddr)->sin6_addr = in6addr_any;
if (bind(ListenSocket, (SOCKADDR*)&LocalAddr, sizeof(LocalAddr)) == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
return 1;
}
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
return 1;
}
// 创建工作线程
for (i = 0; i < 2; i++) {
ThreadHandle = CreateThread(NULL, 0, WorkerThread, CompletionPort, 0, &ThreadId);
if (ThreadHandle == NULL) {
printf("CreateThread failed with error: %d\n", GetLastError());
return 1;
}
CloseHandle(ThreadHandle);
}
// 接受连接并关联到完成端口
while (1) {
AcceptSocket = accept(ListenSocket, (SOCKADDR*)&ClientAddr, NULL);
if (AcceptSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WS
阅读全文