贝贝花花包包店,精品555皮具,钱夹,皮夹

字体: | 推荐给好友 上一篇 | 下一篇

ACE程序员教程-第7章 接受器和连接器:连接建立模式

发布: 2008-6-13 14:17 | 作者: Umar Syyid | 来源: 转载 | 查看: 382次

7.6通过接受器和连接器模式使用简单事件处理器

  有时, ,使用重量级的ACE_Svc_Handler作为接受器和连接器的处理器不仅没有必要,而且会导致代码臃肿。在这样情况下,用户可以使用较轻的ACE_Event_Handler方法来作为反应堆在连接一旦建立时所回调的类。要采用这种方法,程序员需要重载get_handle()方法,并包含将要用于事件处理器的具体底层流。下面的例子有助于演示这些变动。这里我们还编写了新的peer()方法,它返回底层流的引用(reference),就像在ACE_Svc_Handler类中所做的那样。

 

7-10

#include ”ace/Reactor.h”

#include ”ace/Svc_Handler.h”

#include ”ace/Acceptor.h”

#include ”ace/Synch.h”

#include ”ace/SOCK_Acceptor.h”

 

#define PORT_NUM 10101

#define DATA_SIZE 12

 

//forward declaration

class My_Event_Handler;

 

//Create the Acceptor class

typedef ACE_Acceptor

MyAcceptor;

 

//Create an event handler similar to as seen in example 2. We have to

//overload the get_handle() method and write the peer() method. We also

//provide the data member peer_ as the underlying stream which is

//used.

class My_Event_Handler: public ACE_Event_Handler

{

private:

char* data;

 

//Add a new attribute for the underlying stream which will be used by

//the Event Handler

ACE_SOCK_Stream peer_;

 

public:

My_Event_Handler()

{

data= new char[DATA_SIZE];

}

 

int open(void*)

{

cout<<”Connection established”<

 

//Register the event handler with the reactor

ACE_Reactor::instance()->register_handler(this,

ACE_Event_Handler::READ_MASK);

 

return 0;

}

 

int handle_input(ACE_HANDLE)

{

// After using the peer() method of our ACE_Event_Handler to obtain a

//reference to the underlying stream of the service handler class we

//call recv_n() on it to read the data which has been received. This

//data is stored in the data array and then printed out

peer().recv_n(data,DATA_SIZE);

ACE_OS::printf(”<< %s\n”,data);

 

// keep yourself registered with the reactor

return 0;

}

 

// new method which returns the handle to the reactor when it

//asks for it.

ACE_HANDLE get_handle(void) const

{

return this->peer_.get_handle();

}

 

//new method which returns a reference to the peer stream

ACE_SOCK_Stream &peer(void) const

{

return (ACE_SOCK_Stream &) this->peer_;

}

};

 

int main(int argc, char* argv[])

{

ACE_INET_Addr addr(PORT_NUM);

 

//create the acceptor

MyAcceptor acceptor(addr, //address to accept on

ACE_Reactor::instance()); //the reactor to use

 

while(1) /* Start the reactor’s event loop */

ACE_Reactor::instance()->handle_events();

}

44/4<1234
 

评分:0

我来说两句

seccode