最近在看memcached的源码,觉得它那种libevent+多线程的服务器模型真的很不错,我将这个模型封装成一个C++类,根据我的简单测试,这个模型的效率真的很不错,欢迎大家试用。
这个类的使用方法很简单(缺点是不太灵活),只要派生一个类,根据需要重写以下这几个虚函数就行了:
//新建连接成功后,会调用该函数virtual void ConnectionEvent(Conn *conn) { }//读取完数据后,会调用该函数virtual void ReadEvent(Conn *conn) { }//发送完成功后,会调用该函数(因为串包的问题,所以并不是每次发送完数据都会被调用)virtual void WriteEvent(Conn *conn) { }//断开连接(客户自动断开或异常断开)后,会调用该函数virtual void CloseEvent(Conn *conn, short events) { }//发生致命错误(如果创建子线程失败等)后,会调用该函数//该函数的默认操作是输出错误提示,终止程序virtual void ErrorQuit(const char *str);上代码:
头文件:TcpEventServer.h
//TcpEventServer.h#ifndef TCPEVENTSERVER_H_#define TCPEVENTSERVER_H_#include#include #include #include #include #include #include #include #include #include
实现文件:TcpEventServer.cpp
//TcpEventServer.cpp#include "TcpEventServer.h"Conn::Conn(int fd) : m_fd(fd){ m_Prev = NULL; m_Next = NULL;}Conn::~Conn(){}ConnQueue::ConnQueue(){ //建立头尾结点,并调整其指针 m_head = new Conn(0); m_tail = new Conn(0); m_head->m_Prev = m_tail->m_Next = NULL; m_head->m_Next = m_tail; m_tail->m_Prev = m_head;}ConnQueue::~ConnQueue(){ Conn *tcur, *tnext; tcur = m_head; //循环删除链表中的各个结点 while( tcur != NULL ) { tnext = tcur->m_Next; delete tcur; tcur = tnext; }}Conn *ConnQueue::InsertConn(int fd, LibeventThread *t){ Conn *c = new Conn(fd); c->m_Thread = t; Conn *next = m_head->m_Next; c->m_Prev = m_head; c->m_Next = m_head->m_Next; m_head->m_Next = c; next->m_Prev = c; return c;}void ConnQueue::DeleteConn(Conn *c){ c->m_Prev->m_Next = c->m_Next; c->m_Next->m_Prev = c->m_Prev; delete c;}/*void ConnQueue::PrintQueue(){ Conn *cur = m_head->m_Next; while( cur->m_Next != NULL ) { printf("%d ", cur->m_fd); cur = cur->m_Next; } printf("\n");}*/TcpEventServer::TcpEventServer(int count){ //初始化各项数据 m_ThreadCount = count; m_Port = -1; m_MainBase = new LibeventThread; m_Threads = new LibeventThread[m_ThreadCount]; m_MainBase->tid = pthread_self(); m_MainBase->base = event_base_new(); //初始化各个子线程的结构体 for(int i=0; ibase); for(int i=0; i tcpConnect = this; me->base = event_base_new(); if( NULL == me->base ) ErrorQuit("event base new error"); //在主线程和子线程之间建立管道 int fds[2]; if( pipe(fds) ) ErrorQuit("create pipe error"); me->notifyReceiveFd = fds[0]; me->notifySendFd = fds[1]; //让子线程的状态机监听管道 event_set( &me->notifyEvent, me->notifyReceiveFd, EV_READ | EV_PERSIST, ThreadProcess, me ); event_base_set(me->base, &me->notifyEvent); if ( event_add(&me->notifyEvent, 0) == -1 ) ErrorQuit("Can't monitor libevent notify pipe\n");}void *TcpEventServer::WorkerLibevent(void *arg){ //开启libevent的事件循环,准备处理业务 LibeventThread *me = (LibeventThread*)arg; //printf("thread %u started\n", (unsigned int)me->tid); event_base_dispatch(me->base); //printf("subthread done\n");}bool TcpEventServer::StartRun(){ evconnlistener *listener; //如果端口号不是EXIT_CODE,就监听该端口号 if( m_Port != EXIT_CODE ) { sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(m_Port); listener = evconnlistener_new_bind(m_MainBase->base, ListenerEventCb, (void*)this, LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1, (sockaddr*)&sin, sizeof(sockaddr_in)); if( NULL == listener ) ErrorQuit("TCP listen error"); } //开启各个子线程 for(int i=0; i base); //事件循环结果,释放监听者的内存 if( m_Port != EXIT_CODE ) { //printf("free listen\n"); evconnlistener_free(listener); }}void TcpEventServer::StopRun(timeval *tv){ int contant = EXIT_CODE; //向各个子线程的管理中写入EXIT_CODE,通知它们退出 for(int i=0; i base, tv);}void TcpEventServer::ListenerEventCb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data){ TcpEventServer *server = (TcpEventServer*)user_data; //随机选择一个子线程,通过管道向其传递socket描述符 int num = rand() % server->m_ThreadCount; int sendfd = server->m_Threads[num].notifySendFd; write(sendfd, &fd, sizeof(evutil_socket_t));}void TcpEventServer::ThreadProcess(int fd, short which, void *arg){ LibeventThread *me = (LibeventThread*)arg; //从管道中读取数据(socket的描述符或操作码) int pipefd = me->notifyReceiveFd; evutil_socket_t confd; read(pipefd, &confd, sizeof(evutil_socket_t)); //如果操作码是EXIT_CODE,则终于事件循环 if( EXIT_CODE == confd ) { event_base_loopbreak(me->base); return; } //新建连接 struct bufferevent *bev; bev = bufferevent_socket_new(me->base, confd, BEV_OPT_CLOSE_ON_FREE); if (!bev) { fprintf(stderr, "Error constructing bufferevent!"); event_base_loopbreak(me->base); return; } //将该链接放入队列 Conn *conn = me->connectQueue.InsertConn(confd, me); //准备从socket中读写数据 bufferevent_setcb(bev, ReadEventCb, WriteEventCb, CloseEventCb, conn); bufferevent_enable(bev, EV_WRITE); bufferevent_enable(bev, EV_READ); //调用用户自定义的连接事件处理函数 me->tcpConnect->ConnectionEvent(conn);}void TcpEventServer::ReadEventCb(struct bufferevent *bev, void *data){ Conn *conn = (Conn*)data; conn->m_ReadBuf = bufferevent_get_input(bev); conn->m_WriteBuf = bufferevent_get_output(bev); //调用用户自定义的读取事件处理函数 conn->m_Thread->tcpConnect->ReadEvent(conn);} void TcpEventServer::WriteEventCb(struct bufferevent *bev, void *data){ Conn *conn = (Conn*)data; conn->m_ReadBuf = bufferevent_get_input(bev); conn->m_WriteBuf = bufferevent_get_output(bev); //调用用户自定义的写入事件处理函数 conn->m_Thread->tcpConnect->WriteEvent(conn);}void TcpEventServer::CloseEventCb(struct bufferevent *bev, short events, void *data){ Conn *conn = (Conn*)data; //调用用户自定义的断开事件处理函数 conn->m_Thread->tcpConnect->CloseEvent(conn, events); conn->GetThread()->connectQueue.DeleteConn(conn); bufferevent_free(bev);}bool TcpEventServer::AddSignalEvent(int sig, void (*ptr)(int, short, void*)){ //新建一个信号事件 event *ev = evsignal_new(m_MainBase->base, sig, ptr, (void*)this); if ( !ev || event_add(ev, NULL) < 0 ) { event_del(ev); return false; } //删除旧的信号事件(同一个信号只能有一个信号事件) DeleteSignalEvent(sig); m_SignalEvents[sig] = ev; return true;}bool TcpEventServer::DeleteSignalEvent(int sig){ map ::iterator iter = m_SignalEvents.find(sig); if( iter == m_SignalEvents.end() ) return false; event_del(iter->second); m_SignalEvents.erase(iter); return true;}event *TcpEventServer::AddTimerEvent(void (*ptr)(int, short, void *), timeval tv, bool once){ int flag = 0; if( !once ) flag = EV_PERSIST; //新建定时器信号事件 event *ev = new event; event_assign(ev, m_MainBase->base, -1, flag, ptr, (void*)this); if( event_add(ev, &tv) < 0 ) { event_del(ev); return NULL; } return ev;}bool TcpEventServer::DeleteTImerEvent(event *ev){ int res = event_del(ev); return (0 == res);}
测试文件:test.cpp
/*这是一个测试用的服务器,只有两个功能:1:对于每个已连接客户端,每10秒向其发送一句hello, world2:若客户端向服务器发送数据,服务器收到后,再将数据回发给客户端*///test.cpp#include "TcpEventServer.h"#include#include using namespace std;//测试示例class TestServer : public TcpEventServer{private: vector vec;protected: //重载各个处理业务的虚函数 void ReadEvent(Conn *conn); void WriteEvent(Conn *conn); void ConnectionEvent(Conn *conn); void CloseEvent(Conn *conn, short events);public: TestServer(int count) : TcpEventServer(count) { } ~TestServer() { } //退出事件,响应Ctrl+C static void QuitCb(int sig, short events, void *data); //定时器事件,每10秒向所有客户端发一句hello, world static void TimeOutCb(int id, int short events, void *data);};void TestServer::ReadEvent(Conn *conn){ conn->MoveBufferData();}void TestServer::WriteEvent(Conn *conn){}void TestServer::ConnectionEvent(Conn *conn){ TestServer *me = (TestServer*)conn->GetThread()->tcpConnect; printf("new connection: %d\n", conn->GetFd()); me->vec.push_back(conn);}void TestServer::CloseEvent(Conn *conn, short events){ printf("connection closed: %d\n", conn->GetFd());}void TestServer::QuitCb(int sig, short events, void *data){ printf("Catch the SIGINT signal, quit in one second\n"); TestServer *me = (TestServer*)data; timeval tv = { 1, 0}; me->StopRun(&tv);}void TestServer::TimeOutCb(int id, short events, void *data){ TestServer *me = (TestServer*)data; char temp[33] = "hello, world\n"; for(int i=0; i vec.size(); i++) me->vec[i]->AddToWriteBuffer(temp, strlen(temp));}int main(){ printf("pid: %d\n", getpid()); TestServer server(3); server.AddSignalEvent(SIGINT, TestServer::QuitCb); timeval tv = { 10, 0}; server.AddTimerEvent(TestServer::TimeOutCb, tv, false); server.SetPort(2111); server.StartRun(); printf("done\n"); return 0;}
编译与运行命令:
qch@LinuxMint ~/program/ztemp $ g++ TcpEventServer.cpp test.cpp -o test -levent -lpthreadqch@LinuxMint ~/program/ztemp $ ./testpid: 20264new connection: 22connection closed: 22^CCatch the SIGINT signal, quit in one seconddone