/************************************************************************/ /* Copyright (C), 2016-2020, [IT], 保留所有权利; /* 模 块 名:PerSocketContext; /* 描 述:重叠IO缓冲类,每个客户端连接对象类; /* /* 版 本:[V]; /* 作 者:[IT]; /* 日 期:[2/23/2016]; /* /* /* 注 意:; /* /* 修改记录:[IT]; /* 修改日期:; /* 修改版本:; /* 修改内容:; /************************************************************************/ #ifndef __PER_SOCKET_CONTEXT_20160303__ #define __PER_SOCKET_CONTEXT_20160303__ #pragma once #include #include #include "SockAddrIn.h" class PerSocketContext { public: PerSocketContext(SOCKET sock):_socket(sock){ _npendingSize = 0; _ncurSize = 0; _pendingbuf = NULL; memset(&_Overlapped, 0, sizeof(_Overlapped)); } explicit PerSocketContext(SOCKET sock, size_t size): _socket(sock){ _npendingSize = 0; _pendingbuf = NULL; _ncurSize= 0; memset(&_Overlapped, 0, sizeof(_Overlapped)); _data.resize( size ); } PerSocketContext(const PerSocketContext& sbuf){ Copy(sbuf); } PerSocketContext& operator=(const PerSocketContext& sbuf){ return Copy(sbuf); } ~PerSocketContext(){ Free(); } bool IsValid() const { return (_socket != INVALID_SOCKET); } void ReAlloc( size_t count) { _data.resize(count); } void Free() { _data.clear(); if (_pendingbuf) delete []_pendingbuf; _pendingbuf = NULL; } size_t BufferSize() const { return _data.size(); } PerSocketContext& Copy(const PerSocketContext& sbuf) { if ( this != &sbuf ) { _socket = sbuf._socket; _sockAddr = sbuf._sockAddr; if ( !sbuf._data.empty() ) { _data.resize( sbuf._data.size() ); memcpy(&_data[0], &(sbuf._data[0]), _data.size()); } _ncurSize = sbuf._ncurSize; _pendingbuf = NULL; _npendingSize = sbuf._npendingSize; if ( !sbuf._pendingbuf ) { _pendingbuf = new unsigned char[_npendingSize]; memcpy(_pendingbuf, sbuf._pendingbuf,_ncurSize); } } return *this; } // Quick access operator operator SOCKET() { return _socket; } operator SOCKET() const { return _socket; } operator SockAddrIn&() { return _sockAddr; } operator const SockAddrIn&() const { return _sockAddr; } operator LPSOCKADDR() { return _sockAddr; } operator LPWSAOVERLAPPED() { return &_Overlapped; } operator LPBYTE() { return &_data[0]; } bool IsEqual(const PerSocketContext& sbuf) const { return (_socket == sbuf._socket); } bool operator==(const PerSocketContext& sbuf) const { return IsEqual( sbuf ); } bool operator==(SOCKET sock) const { return (_socket == sock); } bool operator!=(const PerSocketContext& sbuf) const { return !IsEqual( sbuf ); } private: SOCKET _socket; SockAddrIn _sockAddr; WSAOVERLAPPED _Overlapped; std::vector _data; PerSocketContext(); public: unsigned char *_pendingbuf; // 超过一次接收包,需要分包处理的包缓冲区; unsigned int _npendingSize; // 总包大小(多个分包); unsigned int _ncurSize; // 当前接收到的分包接收的大小; }; typedef std::list SocketContextList; #endif // __PER_SOCKET_CONTEXT_20160303__