用Reactor框架实现一个简单的tcp服务器

时间:2024-10-25 07:21:20

#include <ace/OS_main.h>
#include <ace/>
#include <ace/Svc_Handler.h>
#include <ace/>
#include <ace/Log_Msg.h>
#include <ace/SOCK_Acceptor.h>
#include <ace/>

class My_Svc_Handler:
    public ACE_Svc_Handler <ACE_SOCK_STREAM,ACE_NULL_SYNCH>
{
    public:
        int open(void*)
        {
            ACE_INET_Addr raddr;
            peer().get_remote_addr(raddr);//get the client addr
            reactor()->register_handler(this,ACE_Event_Handler::READ_MASK);   
            return 0;
        }

        int handle_input(ACE_HANDLE)
        {
            char buffer[64] = {0};
            int len = peer().recv(buffer,sizeof(buffer)-1);
            printf("msg:%s/n",buffer);
            if(len>0)
            {
                return 0;
            }
            else
            {
                return -1;//here to call handle_close() function to disconnect client's linker.
            }
        }

        int handle_close(ACE_HANDLE handle,ACE_Reactor_Mask close_mask)
        {
            ACE_INET_Addr raddr;
            peer().get_remote_addr(raddr);
            ACE_DEBUG ((LM_DEBUG,ACE_TEXT ("(%P|%t) close:%s %d/n"),raddr.get_host_addr(),raddr.get_port_number()));
            peer().close();
            return 0;
        }
};

#define PORT_NUM 10101

typedef ACE_Acceptor<My_Svc_Handler,ACE_SOCK_ACCEPTOR> MyAcceptor;
int main(int argc, char *argv[])
{
    ACE_INET_Addr addr(PORT_NUM);
    MyAcceptor server;

    if((addr)==-1)
    {
        ACE_DEBUG ((LM_DEBUG,"fail to bind/n"));
        return 1;
    }

    while(1){
        ACE_Reactor::instance()->handle_events();
    }
    ();
    return 0;