Winsock IOCP模型(二)

// IOCP2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WinSock2.h>
#include <MSWSock.h>
#include <Windows.h>
#include <process.h>
#pragma comment(lib, "WS2_32.lib")

#define MAX_BUFFER 256
#define MAX_TIMEOUT 1000
#define MAX_SOCKET 1024
#define MAX_THREAD 64
#define MAX_ACCEPT 5

typedef enum _OPERATION_INFO_
{
OP_NULL,
OP_ACCEPT,
OP_READ,
OP_WRITE
}OPERATIONINFO;

typedef struct _PER_HANDLE_DATA_
{
public:
_PER_HANDLE_DATA_()
{
clean();
}
~_PER_HANDLE_DATA_()
{
clean();
}
protected:
void clean()
{
sock = INVALID_SOCKET;
memset(&addr, 0, sizeof(addr));
addr.sin_addr.S_un.S_addr = INADDR_ANY;
addr.sin_port = htons(0);
addr.sin_family = AF_INET;
}
public:
SOCKET sock;
SOCKADDR_IN addr;
}PERHANDLEDATA, *PPERHANDLEDATA;

typedef struct _PER_IO_DTATA_
{
public:
_PER_IO_DTATA_()
{
clean();
}
~_PER_IO_DTATA_()
{
clean();
}
void clean()
{
ZeroMemory(&ol, sizeof(ol));
memset(buf, 0, sizeof(buf));
sAccept = INVALID_SOCKET;
sListen = INVALID_SOCKET;
wsaBuf.buf = buf;
wsaBuf.len = MAX_BUFFER;
opType = OP_NULL;
}
public:
WSAOVERLAPPED ol;
SOCKET sAccept; // Only valid with AcceptEx
SOCKET sListen; // Only valid with AcceptEx
WSABUF wsaBuf;
char buf[MAX_BUFFER];
OPERATIONINFO opType;
}PERIODATA, *PPERIODATA;

HANDLE hThread[MAX_THREAD] = {0};
PERIODATA* pAcceptData[MAX_ACCEPT] = {0};
int g_nThread = 0;
BOOL g_bExitThread = FALSE;
LPFN_ACCEPTEX lpfnAcceptEx = NULL;
LPFN_GETACCEPTEXSOCKADDRS lpfnGetAcceptExSockAddrs = NULL;
GUID GuidAcceptEx = WSAID_ACCEPTEX;
GUID GuidGetAcceptExSockAddrs = WSAID_GETACCEPTEXSOCKADDRS;

unsigned __stdcall ThreadProc(LPVOID lParam);
BOOL PostAccept(PERIODATA* pIoData);

int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested = MAKEWORD(2, 2);
WSADATA wsaData;
if(0 != WSAStartup(wVersionRequested, &wsaData))
{
printf("WSAStartup failed with error code: %d/n", GetLastError());
return EXIT_FAILURE;
}

if(2 != HIBYTE(wsaData.wVersion) || 2 != LOBYTE(wsaData.wVersion))
{
printf("Socket version not supported./n");
WSACleanup();
return EXIT_FAILURE;
}

// Create IOCP
HANDLE hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 0);
if(NULL == hIOCP)
{
printf("CreateIoCompletionPort failed with error code: %d/n", WSAGetLastError());
WSACleanup();
return EXIT_FAILURE;
}

// Create worker thread
SYSTEM_INFO si = {0};
GetSystemInfo(&si);
for(int i = 0; i < (int)si.dwNumberOfProcessors+2; i++)
{
hThread[g_nThread] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, (LPVOID)hIOCP, 0, NULL);
if(NULL == hThread[g_nThread])
{
printf("_beginthreadex failed with error code: %d/n", GetLastError());
continue;
}
++g_nThread;

if(g_nThread > MAX_THREAD)
{
break;
}
}

// Create listen SOCKET
SOCKET sListen = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
if(INVALID_SOCKET == sListen)
{
printf("WSASocket failed with error code: %d/n", WSAGetLastError());
goto EXIT_CODE;
}

// Associate SOCKET with IOCP
if(NULL == CreateIoCompletionPort((HANDLE)sListen, hIOCP, NULL, 0))
{
printf("CreateIoCompletionPort failed with error code: %d/n", WSAGetLastError());
if(INVALID_SOCKET != sListen)
{
closesocket(sListen);
sListen = INVALID_SOCKET;
}
goto EXIT_CODE;
}

// Bind SOCKET
SOCKADDR_IN addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(5050);
if(SOCKET_ERROR == bind(sListen, (LPSOCKADDR)&addr, sizeof(addr)))
{
printf("bind failed with error code: %d/n", WSAGetLastError());
if(INVALID_SOCKET != sListen)
{
closesocket(sListen);
sListen = INVALID_SOCKET;
}
goto EXIT_CODE;
}

// Start Listen
if(SOCKET_ERROR == listen(sListen, 200))
{
printf("listen failed with error code: %d/n", WSAGetLastError());
if(INVALID_SOCKET != sListen)
{
closesocket(sListen);
sListen = INVALID_SOCKET;
}
goto EXIT_CODE;
}

printf("Server start, wait for client to connect .../n");

DWORD dwBytes = 0;
if(SOCKET_ERROR == WSAIoctl(sListen, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidAcceptEx, sizeof(GuidAcceptEx), &lpfnAcceptEx,
sizeof(lpfnAcceptEx), &dwBytes, NULL, NULL))
{
printf("WSAIoctl failed with error code: %d/n", WSAGetLastError());
if(INVALID_SOCKET != sListen)
{
closesocket(sListen);
sListen = INVALID_SOCKET;
}
goto EXIT_CODE;
}

if(SOCKET_ERROR == WSAIoctl(sListen, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidGetAcceptExSockAddrs,
sizeof(GuidGetAcceptExSockAddrs), &lpfnGetAcceptExSockAddrs, sizeof(lpfnGetAcceptExSockAddrs),
&dwBytes, NULL, NULL))
{
printf("WSAIoctl failed with error code: %d/n", WSAGetLastError());
if(INVALID_SOCKET != sListen)
{
closesocket(sListen);
sListen = INVALID_SOCKET;
}
goto EXIT_CODE;
}

// Post MAX_ACCEPT accept
for(int i=0; i<MAX_ACCEPT; i++)
{
pAcceptData[i] = new PERIODATA;
pAcceptData[i]->sListen = sListen;
PostAccept(pAcceptData[i]);
}
// After 1 hour later, Server shutdown.
Sleep(1000 * 60 *60);

EXIT_CODE:
g_bExitThread = TRUE;

PostQueuedCompletionStatus(hIOCP, 0, NULL, NULL);
WaitForMultipleObjects(g_nThread, hThread, TRUE, INFINITE);
for(int i = 0; i < g_nThread; i++)
{
CloseHandle(hThread[g_nThread]);
}

for(int i=0; i<MAX_ACCEPT; i++)
{
if(pAcceptData[i])
{
delete pAcceptData[i];
pAcceptData[i] = NULL;
}
}

if(INVALID_SOCKET != sListen)
{
closesocket(sListen);
sListen = INVALID_SOCKET;
}
CloseHandle(hIOCP); // Close IOCP

WSACleanup();
return 0;
}

BOOL PostAccept(PERIODATA* pIoData)
{
if(INVALID_SOCKET == pIoData->sListen)
{
return FALSE;
}

DWORD dwBytes = 0;
pIoData->opType = OP_ACCEPT;
pIoData->sAccept = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
if(INVALID_SOCKET == pIoData->sAccept)
{
printf("WSASocket failed with error code: %d/n", WSAGetLastError());
return FALSE;
}

if(FALSE == lpfnAcceptEx(pIoData->sListen, pIoData->sAccept, pIoData->wsaBuf.buf, pIoData->wsaBuf.len - ((sizeof(SOCKADDR_IN)+16)*2),
sizeof(SOCKADDR_IN)+16, sizeof(SOCKADDR_IN)+16, &dwBytes, &(pIoData->ol)))
{
if(WSA_IO_PENDING != WSAGetLastError())
{
printf("lpfnAcceptEx failed with error code: %d/n", WSAGetLastError());

return FALSE;
}
}
return TRUE;
}

unsigned __stdcall ThreadProc(LPVOID lParam)
{
HANDLE hIOCP = (HANDLE)lParam;

PERHANDLEDATA* pPerHandleData = NULL;
PERIODATA* pPerIoData = NULL;
WSAOVERLAPPED* lpOverlapped = NULL;
DWORD dwTrans = 0;
DWORD dwFlags = 0;
while(!g_bExitThread)
{
BOOL bRet = GetQueuedCompletionStatus(hIOCP, &dwTrans, (PULONG_PTR)&pPerHandleData, &lpOverlapped, MAX_TIMEOUT);
if(!bRet)
{
// Timeout and exit thread
if(WAIT_TIMEOUT == GetLastError())
{
continue;
}
// Error
printf("GetQueuedCompletionStatus failed with error: %d/n", GetLastError());
continue;
}
else
{
pPerIoData = CONTAINING_RECORD(lpOverlapped, PERIODATA, ol);
if(NULL == pPerIoData)
{
// Exit thread
break;
}

if((0 == dwTrans) && (OP_READ == pPerIoData->opType || OP_WRITE == pPerIoData->opType))
{
// Client leave.
printf("Client: <%s : %d> leave./n", inet_ntoa(pPerHandleData->addr.sin_addr), ntohs(pPerHandleData->addr.sin_port));
closesocket(pPerHandleData->sock);
delete pPerHandleData;
delete pPerIoData;
continue;
}
else
{
switch(pPerIoData->opType)
{
case OP_ACCEPT: // Accept
{
SOCKADDR_IN* remote = NULL;
SOCKADDR_IN* local = NULL;
int remoteLen = sizeof(SOCKADDR_IN);
int localLen = sizeof(SOCKADDR_IN);
lpfnGetAcceptExSockAddrs(pPerIoData->wsaBuf.buf, pPerIoData->wsaBuf.len - ((sizeof(SOCKADDR_IN)+16)*2),
sizeof(SOCKADDR_IN)+16, sizeof(SOCKADDR_IN)+16, (LPSOCKADDR*)&local, &localLen, (LPSOCKADDR*)&remote, &remoteLen);
printf("Client <%s : %d> come in./n", inet_ntoa(remote->sin_addr), ntohs(remote->sin_port));
printf("Recv Data: <%s : %d> %s./n", inet_ntoa(remote->sin_addr), ntohs(remote->sin_port), pPerIoData->wsaBuf.buf);

if(NULL != pPerHandleData)
{
delete pPerHandleData;
pPerHandleData = NULL;
}
pPerHandleData = new PERHANDLEDATA;
pPerHandleData->sock = pPerIoData->sAccept;

PERHANDLEDATA* pPerHandle = new PERHANDLEDATA;
pPerHandle->sock = pPerIoData->sAccept;
PERIODATA* pPerIo = new PERIODATA;
pPerIo->opType = OP_WRITE;
strcpy_s(pPerIo->buf, MAX_BUFFER, pPerIoData->buf);
DWORD dwTrans = strlen(pPerIo->buf);
memcpy(&(pPerHandleData->addr), remote, sizeof(SOCKADDR_IN));
// Associate with IOCP
if(NULL == CreateIoCompletionPort((HANDLE)(pPerHandleData->sock), hIOCP, (ULONG_PTR)pPerHandleData, 0))
{
printf("CreateIoCompletionPort failed with error code: %d/n", GetLastError());
closesocket(pPerHandleData->sock);
delete pPerHandleData;
continue;
}

// Post Accept
memset(&(pPerIoData->ol), 0, sizeof(pPerIoData->ol));
PostAccept(pPerIoData);

// Post Receive
DWORD dwFlags = 0;
if(SOCKET_ERROR == WSASend(pPerHandle->sock, &(pPerIo->wsaBuf), 1,
&dwTrans, dwFlags, &(pPerIo->ol), NULL))
{
if(WSA_IO_PENDING != WSAGetLastError())
{
printf("WSASend failed with error code: %d/n", WSAGetLastError());
closesocket(pPerHandle->sock);
delete pPerHandle;
delete pPerIo;
continue;
}
}
}
break;

case OP_READ: // Read
printf("recv client <%s : %d> data: %s/n", inet_ntoa(pPerHandleData->addr.sin_addr), ntohs(pPerHandleData->addr.sin_port), pPerIoData->buf);
pPerIoData->opType = OP_WRITE;
memset(&(pPerIoData->ol), 0, sizeof(pPerIoData->ol));
if(SOCKET_ERROR == WSASend(pPerHandleData->sock, &(pPerIoData->wsaBuf), 1, &dwTrans, dwFlags, &(pPerIoData->ol), NULL))
{
if(WSA_IO_PENDING != WSAGetLastError())
{
printf("WSASend failed with error code: %d./n", WSAGetLastError());
continue;
}
}
break;

case OP_WRITE: // Write
{
pPerIoData->opType = OP_READ;
dwFlags = 0;
memset(&(pPerIoData->ol), 0, sizeof(pPerIoData->ol));
memset(pPerIoData->buf, 0, sizeof(pPerIoData->buf));
pPerIoData->wsaBuf.buf = pPerIoData->buf;
dwTrans = pPerIoData->wsaBuf.len = MAX_BUFFER;
if(SOCKET_ERROR == WSARecv(pPerHandleData->sock, &(pPerIoData->wsaBuf), 1, &dwTrans, &dwFlags, &(pPerIoData->ol), NULL))
{
if(WSA_IO_PENDING != WSAGetLastError())
{
printf("WSARecv failed with error code: %d./n", WSAGetLastError());
continue;
}
}
}
break;

default:
break;
}
}
}
}
return 0;
}

时间: 2024-10-08 19:03:08

Winsock IOCP模型(二)的相关文章

WinSock IOCP 模型总结(附一个带缓存池的IOCP类)

前言 由于篇幅原因,本文假设你已经熟悉了利用Socket进行TCP/IP编程的基本原理,并且也熟练的掌握了多线程编程技术,太基本的概念我这里就略过不提了,网上的资料应该遍地都是. IOCP全称IOCP全称I/O Completion Port,中文译为I/O完成端口.IOCP是一个异步I/O的Windows I/O模型,它可以自动处理I/O操作,并在I/O操作完成后将完成通知发送给用户.本文主要介绍基于IOCP的网络I/O操作(即socket的Accept.Send.Recv和Close等).W

Windows完成端口 IOCP模型(二)

1详解完成端口基本使用 1创建完成端口 HANDLE iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,0,0); 参数其实就是-1,0,0,0. 最后一个参数代表的就是 NumberOfConcurrentThreads,就是允许应用同时执行的线程数量, 未来避免上下文切换,就是说让每个CPU只允许一个线程,设置为0 就是有多少处理器,就有多少工作线程. 原因就是如果一台机器有两个CPU(两核),如果让系统同时运行的 线程,多于本机

Winsock IOCP模型(四篇)

http://blog.csdn.net/visualeleven/article/details/6041893 http://blog.csdn.net/visualeleven/article/details/6088590 http://blog.csdn.net/visualeleven/article/details/5991743 http://blog.csdn.net/visualeleven/article/details/6011417

winsock编程IOCP模型实现代码

winsock编程IOCP模型实现代码 话不多说,上代码.借鉴<windows核心编程>部分源码和CSDN小猪部分代码. stdafx.h依赖头文件: 1 #include <iostream> 2 #include <WinSock2.h> 3 #include <MSWSock.h> 4 #include <vector> 5 #include "Singleton.h" 6 #include "IOCPWrap

IOCP模型与网络编

一.前言:        在老师分配任务(“尝试利用IOCP模型写出服务端和客户端的代码”)给我时,脑子一片空白,并不知道什么是IOCP模型,会不会是像软件设计模式里面的工厂模式,装饰模式之类的那些呢?嘿嘿,不过好像是一个挺好玩的东西,挺好奇是什么东西来的,又是一个新知识啦~于是,开始去寻找一大堆的资料,为这个了解做准备,只是呢,有时还是想去找一本书去系统地学习一下,毕竟网络的资料还是有点零散.话说,本人学习这个模型的基础是,写过一个简单的Socket服务器及客户端程序,外加一个简单的Socke

IOCP模型与网络编程

IOCP模型与网络编程 一.前言:        在老师分配任务("尝试利用IOCP模型写出服务端和客户端的代码")给我时,脑子一片空白,并不知道什么是IOCP模型,会不会是像软件设计模式里面的工厂模式,装饰模式之类的那些呢?嘿嘿,不过好像是一个挺好玩的东西,挺好奇是什么东西来的,又是一个新知识啦~于是,开始去寻找一大堆的资料,为这个了解做准备,只是呢,有时还是想去找一本书去系统地学习一下,毕竟网络的资料还是有点零散.话说,本人学习这个模型的基础是,写过一个简单的Socket服务器及客

IOCP模型总结(总结回顾)

IOCP旧代码重提,最近一直在玩其他方面的东东,时不时回顾一下,收益多多. IOCP(I/O Completion Port,I/O完成端口)是性能最好的一种I/O模型.它是应用程序使用线程池处理异步I/O请求的一种机制.在处理多个并发的异步I/O请求时,以往的模型都是在接收请求是创建一个线程来应答请求.这样就有很多的线程并行地运行在系统中.而这些线程都是可运行的,Windows内核花费大量的时间在进行线程的上下文切换,并没有多少时间花在线程运行上.再加上创建新线程的开销比较大,所以造成了效率的

IOCP模型

IOCP http://blog.csdn.net/zhongguoren666/article/details/7386592 Winsock IO模型之IOCP模型 http://blog.csdn.net/lostyears/article/details/7436802

Nginx源码分析 - Nginx启动以及IOCP模型

Nginx 源码分析 - Nginx启动以及IOCP模型 版本及平台信息 本文档针对Nginx1.11.7版本,分析Windows下的相关代码,虽然服务器可能用linux更多,但是windows平台下的代码也基本相似 ,另外windows的IOCP完成端口,异步IO模型非常优秀,很值得一看. Nginx启动 曾经有朋友问我,面对一个大项目的源代码,应该从何读起呢?我给他举了一个例子,我们学校大一大二是在紫金港校区,到了 大三搬到玉泉校区,但是大一的时候也会有时候有事情要去玉泉办.偶尔会去玉泉,但