Our new directed_client.cpp is very much like our previous one. The primary difference is the addition of a timeout to the recv() call so that we can exit somewhat gracefully if the server doesn't like what we have to say.
#include "ace/SOCK_Dgram.h"
#include "ace/INET_Addr.h"
static const u_short PORT = ACE_DEFAULT_SERVER_PORT;
int main (int argc, char *argv[])
{
ACE_INET_Addr local ((u_short) 0);
ACE_INET_Addr remote (PORT, argc > 1 ? argv[1] : "localhost");
ACE_SOCK_Dgram dgram;
if (dgram.open (local) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "open"),
-1);
}
char buf[512];
/*
In order to conform to the "protocol"
requried by the server,
we allow the user to specify a signature.
A default matching
the server's default is also available.
*/
sprintf (buf, argc > 2 ? argv[2] : "Hello World!");
if (dgram.send (buf, strlen (buf) + 1, remote) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "send"),
-1);
}
/*
Because we may have sent a signature that
the server doesn't
honor, we have to have some way to get
out of the recv().
Most ACE objects that have potential for
infinite blocking
give you the option of providing a timeout.
recv() is no
exception. Here, we construct an
ACE_Time_Value representing
two seconds and no micro-seconds.
If recv() fails to get
a response within the two seconds, it
will return -1.
*/
ACE_Time_Value timeout (2, 0);
if (dgram.recv (buf, sizeof (buf), remote, 0, &timeout)
== -1)
{
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "recv"),
-1);
}
ACE_DEBUG ((LM_DEBUG, "(%P|%t) The server said (%s)\n", buf));
return (0);
}
On the next page, we see that the directed_client gets similar upgrades.