📄 tcpserver.h
字号:
////////////////////////////////////////////////////////////////////////////////
// select I/O 模型的TCP Server
////////////////////////////////////////////////////////////////////////////////
// Author : 黎达文
// Description :
//
// Version :
//
// Standard include files :
//
// Start Date : 2003年12月3日
//
// Change Log : 2003年12月3日 by 黎达文 -- Created
////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_TCPSERVER_H
#define INCLUDED_TCPSERVER_H
#if defined(HAS_PRAGMA_ONCE)
#pragma PRAGMA_ONCE_DECLARE
#endif
#include "socketex.h"
#include "patterns/acl/seqid.h"
#include "patterns/util/logcontrol.h"
namespace acl
{
//if somebody want to support more client, redefine FD_SETSIZE please,
//but make sure redefine before include winsock2.h and this file
static const int MAX_CLIENT = (FD_SETSIZE-2);
//表示客户端的数据结构
class TcpClientData
{
public:
TcpClientData(){}
TcpClientData &operator = (const TcpClientData &other)
{
m_clientid = other.m_clientid;
m_socketid = other.m_socketid;
return *this;
}
unsigned int getId() const { return m_clientid; }
SOCKET getsocket()const { return m_socketid; }
unsigned int m_clientid; // the identify of this client
AcceptedSocket m_socketid;
};
// 使用select I/O模型的服务器模块
class TcpServer : public CTThreadExtend
, public stk::LogControl // log
{
public:
TcpServer();
TcpServer(u_short port, const char *addr = NULL);
virtual ~TcpServer();
//start the service
bool start();
bool start(u_short port, const char *addr = NULL);
//stop the service
void stop(int timeout = INFINITE);
//main interface for user call :
int send(unsigned int clientid, const char *buf, int buf_size);
//support for owner check the server status
bool binded() { return m_binded; }
DWORD getError() { return m_comm.getError(); }
bool closeClient(int clientId);
protected:
private:
// initialize object state
void init();
virtual bool onAccept(const TcpClientData &client) { return true; }
virtual void onBroken(const TcpClientData &client) { }
//onReceive must return the following result
//RECV_OK // recv ok
//RECV_CLOSE // connection closed
//RECV_SOCKET_ERROR // socket error
//RECV_USER_ERROR // user error < 0
virtual int onReceive(const TcpClientData &client) = 0;
virtual bool reparable(int errcode);
//start the listen thread
void startListen();
void makeSelector();
void recover();
//client manager functions
bool insertClient(const AcceptedSocket &client);
void eraseClient(int index);
void cleanClients();
AcceptedSocket getClientSocket(unsigned int clientid);
void checkClientEvent();
virtual void threadProcess();
private:
ServerSocket m_comm; //communication component
TcpClientData m_client[MAX_CLIENT];
SequenceGenerator m_seqGenerator;
bool m_binded;
bool m_running;
bool m_exit_signaled;
//connected client count
int m_clients;
fd_set m_readfds;
};
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -