目标:利用Reactor框架构建一个能处理多个连接的服务器。
我们的方案:从 ACE_Event_Handler 类派生两个事件处理类,分工,"连接接受"和“连接服务"。 //用于接受连接的事件处理器(反应器) class ClientAcceptor : public ACE_Event_Handler { public: virtual ~ClientAcceptor(void) { this->handle_close(ACE_INVALID_HANDLE,0); } int open(const ACE_INET_Addr& listen_addr) { if (this->acceptor_.open(listen_addr,1) == -1) ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("%p/n"), ACE_TEXT("acceptor.open")), -1); //针对接受事件向反应器登记 return this->reactor()->register_handler(this,ACE_Event_Handler::ACCEPT_MASK); } protected: ACE_SOCK_Acceptor acceptor_; public: // Get this handler's I/O handle. virtual ACE_HANDLE get_handle(void) const { return this->acceptor_.get_handle(); } // Called when a connection is ready to accept. virtual int handle_input(ACE_HANDLE fd) { //ClientService* client; //ACE_NEW_RETURN(client,ClientService,-1); ClientService *client = new ClientService(); auto_ptr<ClientService> p(client);//这个auto_ptr应该具有引用计数的功能 if (this->acceptor_.accept(client->peer()) == -1) return -1; p.release(); client->reactor(this->reactor()); if (client->open() == -1) client->handle_close(ACE_INVALID_HANDLE,0); return 0; } // Called when this handler is removed from the ACE_Reactor. virtual int handle_close(ACE_HANDLE handle,ACE_Reactor_Mask close_mask) { if (this->acceptor_.get_handle() != ACE_INVALID_HANDLE) { ACE_Reactor_Mask m = ACE_Event_Handler::ACCEPT_MASK | ACE_Event_Handler::DONT_CALL; this->reactor()->remove_handler(this,m); this->acceptor_.close(); } return 0; } }; //服务处理器 //每个连接使用单独的服务处理器对象 class ClientService : public ACE_Event_Handler { protected: ACE_SOCK_Stream sock_; public: //返回ACE_SOCK_Stream对象引用 ACE_SOCK_Stream& peer(void) { return this->sock_; } int open(void) { //针对输入事件向反应器登记 return this->reactor()->register_handler(this,ACE_Event_Handler::READ_MASK); } // Get this handler's I/O handle. virtual ACE_HANDLE get_handle(void) const { return this->sock_.get_handle(); } // Called when input is available from the client. virtual int handle_input(ACE_HANDLE fd) { const size_t INPUT_SIZE = 4096; char buffer[INPUT_SIZE]; ssize_t recv_cnt; if ((recv_cnt = this->sock_.recv(buffer,sizeof (buffer))) <= 0) { //接受到的数据为0个字节,表明对端已关闭其socket。 //返回-1,表示工作已完成。 return -1; } //在这里你可以对接收的数据进行处理 //... return 0; } // Called when this handler is removed from the ACE_Reactor. virtual int handle_close(ACE_HANDLE handle,ACE_Reactor_Mask close_mask) { mask = ACE_Event_Handler::ALL_EVENTS_MASK | ACE_Event_Handler::DONT_CALL; this->reactor()->remove_handler(this,mask); this->sock_.close(); delete this; return 0; } }; //好了构建好了你的应用,你可以启动它了。 ACE_INET_Addr addr_to_listen(50000,ACE_LOCALHOST); ClientAcceptor acceptor; acceptor.reactor(ACE_Reactor::instance()); //开始监听,向反应器进行登记,请求它在可以接受新连接时回调自己。 if (acceptor.open(addr_to_listen) == -1) return 1; //进入反应器事件循环 ACE_Reactor::instance()->run_reactor_event_loop(); |