114 lines
2.1 KiB
C++
114 lines
2.1 KiB
C++
#pragma once
|
||
#include <vector>
|
||
#include <mutex>
|
||
#include <thread>
|
||
#include <atomic>
|
||
#include <condition_variable>
|
||
#ifndef _WIN32
|
||
#include <sys/types.h>
|
||
#include <sys/socket.h>
|
||
#endif // !_WIN32
|
||
|
||
#include "IYTCPServer.h"
|
||
|
||
typedef std::function<void (const TCPClient* pClient, const char* pData, const unsigned int nLen)> FunTCPServerRecv;
|
||
|
||
#define RECV_DATA_LEN 12 * 1024 * 1024
|
||
|
||
#ifdef _WIN32
|
||
|
||
#define FD_SETSIZE 1024
|
||
#define _WINSOCK_DEPRECATED_NO_WARNINGS
|
||
#include <WinSock2.h>
|
||
#include <windows.h>
|
||
|
||
#pragma comment(lib, "ws2_32.lib")
|
||
|
||
#else
|
||
#define SOCKET int
|
||
#define INVALID_SOCKET (SOCKET)(~0)
|
||
#define SOCKET_ERROR (-1)
|
||
#endif
|
||
|
||
enum WORK_STATUS
|
||
{
|
||
WORK_INIT,
|
||
WORK_RUNING,
|
||
WORK_WAITSINGAL,
|
||
WORK_CLOSE,
|
||
WORK_EXIT,
|
||
};
|
||
|
||
class CYServerTask
|
||
{
|
||
public:
|
||
CYServerTask();
|
||
~CYServerTask();
|
||
|
||
/// 开始任务
|
||
bool StartTask(FunTCPServerRecv fRecv, bool bRecvSelfProtocol = false);
|
||
|
||
///设置异常处理回调(给CYTCPServer使用)
|
||
void SetExceptionCallback(std::function<void(const TCPClient*)> fException);
|
||
|
||
///ֹͣ<CDA3><D6B9><EFBFBD><EFBFBD>
|
||
bool StopTask();
|
||
|
||
///添加客户端
|
||
bool AddClient(TCPClient* pClient);
|
||
|
||
///移除客户端
|
||
bool DelClient(const TCPClient* pClient);
|
||
|
||
///获取Task中客户端的数目
|
||
int GetClientNum();
|
||
|
||
private:
|
||
void _OnProcessEvent();
|
||
|
||
bool _OnProcessData(TCPClient* pClient);
|
||
|
||
private:
|
||
|
||
///客户端存储vector
|
||
std::mutex m_mClient;
|
||
std::vector<TCPClient *> m_vClient;
|
||
|
||
///select 监听 注释:和m_vClient使用同一把锁
|
||
int m_maxSocket;
|
||
fd_set m_fdRead;
|
||
fd_set m_fdExp;
|
||
|
||
///线程管理
|
||
std::thread* m_tTask;
|
||
bool m_bWork;
|
||
WORK_STATUS m_eWorkStatus;
|
||
|
||
//工作信号
|
||
std::mutex m_mutexWork;
|
||
std::condition_variable m_cvWork;
|
||
|
||
//处理回调[接口]
|
||
private:
|
||
//处理回调[接口]
|
||
FunTCPServerRecv m_fRecv;
|
||
std::function<void(const TCPClient*)> m_fException;
|
||
char* m_pRecvBuf;
|
||
|
||
std::atomic<bool> m_bUseProtocol;
|
||
|
||
struct ProtocolHead
|
||
{
|
||
int nHead;
|
||
int nTime;
|
||
int nCmd;
|
||
int nDef;
|
||
int nLen;
|
||
int nTail;
|
||
char pData[RECV_DATA_LEN];
|
||
};
|
||
|
||
ProtocolHead* m_pProtocalHead;
|
||
|
||
};
|