首先你因该针对你应用从ACE_Service_Handler派生:
#include <ace/Asynch_IO.h>
#include <ace/Message_Block.h>
#include <ace/OS.h>
class HA_Proactive_Service : public ACE_Service_Handler
{
private:
ACE_Asynch_Read_Stream reader_;
ACE_Asynch_Write_Stream writer_;
public:
~HA_Proactive_Service()
{
if (this->handle() != ACE_INVALID_HANDLE)
ACE_OS::closesocket(this->handle());
}
virtual void open(ACE_HANDLE new_handle, ACE_Message_Block &message_block)
{
this->handle(new_handle);//新的socket句柄产生了,我们在析构函数里管理了它
if (this->reader_.open(*this) != 0 ||
this->writer_.open(*this) != 0)
{
ACE_ERROR((LM_ERROR,
ACE_TEXT("%p
"),
ACE_TEXT("HA_Proactive_Service open")));
delete this;
return;
}
//你可以在这里用this->reader_读数据,或者用this->writer_写数据
//这就是步骤的第一步(发起I/O操作)
//。。。
return;
}
// This method will be called when an asynchronous read
// completes on a stream.
virtual void handle_read_stream(const ACE_Asynch_Read_Stream::Result &result)
{
//数据读完了,我取得了读到的数据mb
ACE_Message_Block& mb = result.message_block();
//怎么处理这些数据呢,你看着办吧。
//。。。
return;
}
// This method will be called when an asynchronous write
// completes on a stream.
virtual void handle_write_stream(const ACE_Asynch_Write_Stream::Result &result)
{
//数据写完了,你该释放消息块。
result.message_block().release();
//。。。
return;
}
//还可重载更多回调函数
};
你可以Asynch_Connector和Asynch_Acceptor都依赖HA_Proactive_Service(确切的说是ACE_Service_Handler,HA_Proactive_Service派生自ACE_Service_Handler),所以HA_Proactive_Service可以分成两个不同类,分别根据需要为Asynch_Connector和Asynch_Acceptor服务(这里只是合二为一做示例)。
Asynch_Connector是这样的:
#include <ace/INET_Addr.h>
#include <ace/Proactor.h>
#include <ace/Asynch_Connector.h>
#include "HA_Proactive_Service.h"
ACE_INET_Addr peer_addr(50000, ACE_LOCALHOST); // Set up peer addr
ACE_Asynch_Connector<HA_Proactive_Service> aio_connect;
aio_connect.connect(peer_addr);
ACE_Proactor::instance()->proactor_run_event_loop ();
Asynch_Acceptor是这样的:
#include <ace/INET_Addr.h>
#include <ace/Proactor.h>
#include <ace/Asynch_Acceptor.h>
#include "HA_Proactive_Service.h"
ACE_INET_Addr peer_addr(50000, ACE_LOCALHOST); // Set up peer addr
Asynch_Acceptor<HA_Proactive_Service> aio_acceptor
aio_acceptor.open(peer_addr);
ACE_Proactor::instance()->proactor_run_event_loop ();