Merge pull request #2216 from jwillemsen/jwi-cxxversionchecks
[ACE_TAO.git] / ACE / examples / APG / Reactor / Client.cpp
blobecf8925d1be203ad147256ca856136ef43aa8d3c
1 /**
2 * A simple client program using ACE_Svc_Handler and ACE_Connector.
3 */
5 #include "ace/OS_NS_stdio.h"
6 #include "ace/OS_NS_errno.h"
7 #include "ace/OS_NS_string.h"
8 #include "ace/OS_NS_sys_time.h"
9 #include "Client.h"
11 // Listing 2 code/ch07
12 int Client::open (void *p)
14 ACE_Time_Value iter_delay (2); // Two seconds
15 if (super::open (p) == -1)
16 return -1;
17 this->notifier_.reactor (this->reactor ());
18 this->msg_queue ()->notification_strategy (&this->notifier_);
19 this->iterations_ = 0;
20 return this->reactor ()->schedule_timer
21 (this, 0, ACE_Time_Value::zero, iter_delay);
23 // Listing 2
25 // Listing 3 code/ch07
26 int Client::handle_input (ACE_HANDLE)
28 char buf[64];
29 ssize_t recv_cnt = this->peer ().recv (buf, sizeof (buf) - 1);
30 if (recv_cnt > 0)
32 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%.*C"),
33 static_cast<int> (recv_cnt),
34 buf));
35 return 0;
38 if (recv_cnt == 0 || ACE_OS::last_error () != EWOULDBLOCK)
40 this->reactor ()->end_reactor_event_loop ();
41 return -1;
43 return 0;
45 // Listing 3
47 // Listing 4 code/ch07
48 int Client::handle_timeout(const ACE_Time_Value &, const void *)
50 if (++this->iterations_ >= ITERATIONS)
52 this->peer ().close_writer ();
53 return 0;
56 ACE_Message_Block *mb = 0;
57 ACE_NEW_RETURN (mb, ACE_Message_Block (128), -1);
58 int nbytes = ACE_OS::sprintf
59 (mb->wr_ptr (), "Iteration %d\n", this->iterations_);
60 ACE_ASSERT (nbytes > 0);
61 mb->wr_ptr (static_cast<size_t> (nbytes));
62 this->putq (mb);
63 return 0;
65 // Listing 4
67 // Listing 5 code/ch07
68 int Client::handle_output (ACE_HANDLE)
70 ACE_Message_Block *mb = 0;
71 ACE_Time_Value nowait (ACE_OS::gettimeofday ());
72 while (-1 != this->getq (mb, &nowait))
74 ssize_t send_cnt =
75 this->peer ().send (mb->rd_ptr (), mb->length ());
76 if (send_cnt == -1)
77 ACE_ERROR ((LM_ERROR,
78 ACE_TEXT ("(%P|%t) %p\n"),
79 ACE_TEXT ("send")));
80 else
81 mb->rd_ptr (static_cast<size_t> (send_cnt));
82 if (mb->length () > 0)
84 this->ungetq (mb);
85 break;
87 mb->release ();
89 if (this->msg_queue ()->is_empty ())
90 this->reactor ()->cancel_wakeup
91 (this, ACE_Event_Handler::WRITE_MASK);
92 else
93 this->reactor ()->schedule_wakeup
94 (this, ACE_Event_Handler::WRITE_MASK);
95 return 0;
97 // Listing 5
99 // Listing 6 code/ch07
100 int ACE_TMAIN (int, ACE_TCHAR *[])
102 ACE_INET_Addr port_to_connect (ACE_TEXT ("HAStatus"), ACE_LOCALHOST);
103 ACE_Connector<Client, ACE_SOCK_CONNECTOR> connector;
104 Client client;
105 Client *pc = &client;
106 if (connector.connect (pc, port_to_connect) == -1)
107 ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
108 ACE_TEXT ("connect")), 1);
110 ACE_Reactor::instance ()->run_reactor_event_loop ();
111 return (0);
113 // Listing 6
115 // Listing 7 code/ch07
116 // Listing 7