70 lines
1.7 KiB
C++
70 lines
1.7 KiB
C++
#pragma once
|
|
#define WIN32_LEAN_AND_MEAN
|
|
|
|
#include <WinSock2.h>
|
|
#include <mswsock.h>
|
|
#include <map>
|
|
#include <mutex>
|
|
#include <functional>
|
|
#include "md5.h"
|
|
#include "AES.h"
|
|
|
|
|
|
#pragma comment(lib, "ws2_32.lib")
|
|
#pragma comment(lib, "Mswsock.lib")
|
|
|
|
using namespace std;
|
|
|
|
#pragma warning(disable:4996)
|
|
|
|
class SocketS
|
|
{
|
|
private:
|
|
|
|
struct MsgHead
|
|
{
|
|
int isStr = 0;
|
|
int bufLen = 0;
|
|
time_t tm = 0;
|
|
char token[34] = { 0 };
|
|
};
|
|
|
|
struct clienInfo
|
|
{
|
|
SOCKET c_Sock;
|
|
OVERLAPPED c_Olp;
|
|
int Rbuflen = 0;
|
|
MsgHead h;
|
|
char buff[10240] = { 0 };
|
|
};
|
|
|
|
BOOL g_flag = 0; //状态
|
|
HANDLE hPort = NULL; //完成端口句柄
|
|
int g_count = 1; //当前客户端ID
|
|
map<int, clienInfo>ClienMap;//所有客户端
|
|
std::thread *ListenClien; //监听线程
|
|
int Count = 0; //工作者线程多少个
|
|
mutex Lock; //线程锁
|
|
function<VOID(int,char*,int)> Rfunc = NULL; //接收数据的回调函数
|
|
function<VOID(int)> Cfunc = NULL; //客户端关闭的回调函数
|
|
|
|
static DWORD WINAPI ThreadProc(LPVOID lpParameter); //工作者线程
|
|
int PostSend(int index, const char* buf, int len); //给指定客户端发送数据
|
|
VOID PostRecv(int index); //投递消息
|
|
BOOL CheckHead(MsgHead* h); //检查消息头
|
|
VOID Listens(); //监听消息函数
|
|
|
|
public:
|
|
SocketS(); //构造
|
|
BOOL Creat(int Prot); //创建服务端
|
|
void Close(); //关闭服务端
|
|
VOID SetRecvFunc(function<VOID(int, char*, int)> fun); //设置接收消息的回调函数
|
|
VOID SetCloseFunc(function<VOID(int)> fun); //设置关闭客户端的回调函数
|
|
VOID GetClienName(int index, string& IP, int& Prot); //获取客户端IP和端口
|
|
int SendData(int index, const char* buf, int len, int isStr = 0); //发送数据包
|
|
BOOL SendStr(int index, string str); //发送字符串
|
|
VOID CloseClien(int index); //关闭指定客户端
|
|
|
|
};
|
|
|