1 #include "ace/OS_NS_errno.h"
2 #include "ace/OS_NS_sys_time.h"
3 #include "ace/os_include/os_netdb.h"
4 #include "ClientService.h"
7 #include "ace/Log_Msg.h"
8 #include "ace/INET_Addr.h"
9 #include "ace/SOCK_Acceptor.h"
10 #include "ace/Reactor.h"
11 #include "ace/Acceptor.h"
13 typedef ACE_Acceptor
<ClientService
, ACE_SOCK_ACCEPTOR
>
17 // Listing 4 code/ch07
19 ClientService::open (void *p
)
21 if (super::open (p
) == -1)
24 ACE_TCHAR peer_name
[MAXHOSTNAMELEN
];
25 ACE_INET_Addr peer_addr
;
26 if (this->peer ().get_remote_addr (peer_addr
) == 0 &&
27 peer_addr
.addr_to_string (peer_name
, MAXHOSTNAMELEN
) == 0)
29 ACE_TEXT ("(%P|%t) Connection from %s\n"),
35 // Listing 5 code/ch07
37 ClientService::handle_input (ACE_HANDLE
)
39 const size_t INPUT_SIZE
= 4096;
40 char buffer
[INPUT_SIZE
];
41 ssize_t recv_cnt
, send_cnt
;
43 recv_cnt
= this->peer ().recv (buffer
, sizeof(buffer
));
47 ACE_TEXT ("(%P|%t) Connection closed\n")));
52 this->peer ().send (buffer
,
53 static_cast<size_t> (recv_cnt
));
54 if (send_cnt
== recv_cnt
)
56 if (send_cnt
== -1 && ACE_OS::last_error () != EWOULDBLOCK
)
57 ACE_ERROR_RETURN ((LM_ERROR
,
58 ACE_TEXT ("(%P|%t) %p\n"),
63 ACE_Message_Block
*mb
= 0;
65 static_cast<size_t> ((recv_cnt
- send_cnt
));
66 ACE_NEW_RETURN (mb
, ACE_Message_Block (remaining
), -1);
67 mb
->copy (&buffer
[send_cnt
], remaining
);
68 int output_off
= this->msg_queue ()->is_empty ();
69 ACE_Time_Value
nowait (ACE_OS::gettimeofday ());
70 if (this->putq (mb
, &nowait
) == -1)
73 ACE_TEXT ("(%P|%t) %p; discarding data\n"),
74 ACE_TEXT ("enqueue failed")));
79 return this->reactor ()->register_handler
80 (this, ACE_Event_Handler::WRITE_MASK
);
85 // Listing 6 code/ch07
87 ClientService::handle_output (ACE_HANDLE
)
89 ACE_Message_Block
*mb
= 0;
90 ACE_Time_Value
nowait (ACE_OS::gettimeofday ());
91 while (-1 != this->getq (mb
, &nowait
))
94 this->peer ().send (mb
->rd_ptr (), mb
->length ());
97 ACE_TEXT ("(%P|%t) %p\n"),
100 mb
->rd_ptr (static_cast<size_t> (send_cnt
));
101 if (mb
->length () > 0)
108 return (this->msg_queue ()->is_empty ()) ? -1 : 0;
112 // Listing 7 code/ch07
114 ClientService::handle_close (ACE_HANDLE h
, ACE_Reactor_Mask mask
)
116 if (mask
== ACE_Event_Handler::WRITE_MASK
)
118 return super::handle_close (h
, mask
);
122 // Listing 2 code/ch07
123 int ACE_TMAIN (int, ACE_TCHAR
*[])
125 ACE_INET_Addr
port_to_listen ("HAStatus");
126 ClientAcceptor acceptor
;
127 if (acceptor
.open (port_to_listen
,
128 ACE_Reactor::instance (),
132 ACE_Reactor::instance ()->run_reactor_event_loop ();
138 // Listing 8 code/ch07