完成端口(IOCP)的实现

发布时间:2021-06-06

整理的一个简单的完成端口类


#ifndef _COMPLETIONPORT_H
#define _COMPLETIONPORT_H

#include <winsock2.h>
#include <mswsock.h>
#include <process.h>
#include <vector>
#include <map>
#include <deque>
#include <set>

#define MAX_MEM_COUNT 1000
#define MAX_BUF 1024
#define RECV_COUNT 5

#pragma pack (push)
#pragma pack (1)

enum
{
IO_ACCEPT,
IO_READ,
IO_WRITE,
IO_END,
};

enum
{
IO_SEND,
IO_RECV
};


//单IO数据
typedef struct _PER_IO_CONTEXT
{
WSAOVERLAPPED ol;
char buf[MAX_BUF];
WSABUF wsabuf;
SOCKET sClient;
DWORD id;
BYTE IoOperation;
}PER_IO_CONTEXT,*LPPER_IO_CONTEXT;

//完成键(单句炳数据)
typedef struct _PER_HANDLE_CONTEXT
{
SOCKET IoSocket;

}PER_HANDLE_CONTEXT,*LPPER_HANDLE_CONTEXT;

static GUID g_GUIDAcceptEx = WSAID_ACCEPTEX;
static GUID g_GUIDGetAcceptExSockaddrs = WSAID_GETACCEPTEXSOCKADDRS;

//工作线程类
class WorkThread
{
private:
HANDLE m_hThread;
unsigned int m_nThreadID;
unsigned int (__stdcall*pnThreadFun)(LPVOID param);
void* m_pParam;
public:
WorkThread();
WorkThread(unsigned int (__stdcall*pnThreadFun)(LPVOID param),void* param);
~WorkThread();
bool Init();
void Start();
void Stop();
void SendMessage(UINT Msg, WPARAM wParam, LPARAM lParam);
void SetPriority(int priority);
};

//客户端链接类
class NetClient
{
public:
SOCKET m_socket;
SOCKADDR_IN m_address;
LPPER_HANDLE_CONTEXT m_pComKey;
NetClient();
NetClient(int socket);
~NetClient();
void SendPacket(void* pData,bool encrypt = TRUE);
void Disconnect();
};

//完成端口类
class NetCompletionPort
{
private:
LPFN_ACCEPTEX m_pAcceptEx;
LPFN_GETACCEPTEXSOCKADDRS m_pGetAcceptExSockaddrs;
HANDLE m_comPort;
int m_port;
SOCKET m_listenSocket;
HANDLE m_hEventListen;
bool m_isCreate;

std::vector<WorkThread*>* m_pWorkThreadList;
WorkThread* m_pThreadAccept;

bool InitWinSock();
bool InitListenSocket();
bool InitListenEvent();
bool InitWorkThread();

std::map<int,NetClient*>* m_pClientList;
CRITICAL_SECTION m_clientListSection;
void DeleteClient(NetClient* pClient);
void AddClient(NetClient* pClient);
NetClient* GetClient(int socket);

std::set<LPPER_IO_CONTEXT>* m_pConnectList;
CRITICAL_SECTION m_conSection;
void InsertConnect(LPPER_IO_CONTEXT pConnect);
void ReleaseConnect(int socket);

std::deque<LPPER_IO_CONTEXT&g
t;* m_pIoMemList;
std::deque<LPPER_HANDLE_CONTEXT>* m_pHandleMemList;
CRITICAL_SECTION m_ioMenListSection;
CRITICAL_SECTION m_hdM

完成端口(IOCP)的实现.doc 将本文的Word文档下载到电脑

精彩图片

热门精选

大家正在看

× 游客快捷下载通道(下载后可以自由复制和排版)

限时特价:7 元/份 原价:20元

支付方式:

开通VIP包月会员 特价:29元/月

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:fanwen365 QQ:370150219