summaryrefslogtreecommitdiff
path: root/docs/tutorials/004/client.cpp
blob: 295d8131f8f4a541d891a1c842efaa98f12f44af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// $Id$

#include "ace/SOCK_Connector.h"
#include "ace/SString.h"

class Client : private ACE_SOCK_Stream
{
public:
  ACE_SOCK_Stream::close;	// promote to public

  Client(void);
  Client( const char * server, u_short port );

  int open( const char * server, u_short port );

  inline int initialized(void) { return mInitialized; }
  inline int error(void)       { return mError; }

  Client & operator<<( ACE_SString & str );
  Client & operator<<( char * str );
  Client & operator<<( int  n );

  class Error {};

protected:

private:
  unsigned char mInitialized;
  unsigned char mError;
};

Client::Client(void)
{
  mInitialized = 0;
  mError = 0;
}

Client::Client( const char * server, u_short port )
{
  mInitialized = 0;
  mError = 0;
  (void)open(server,port);
}

int Client::open( const char * server, u_short port )
{
  ACE_SOCK_Connector connector;
  ACE_INET_Addr addr (port, server);

  if (connector.connect (*this, addr) == -1)
  {
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "open"), -1);
  }

  mInitialized = 1;

  return(0);
}

Client & Client::operator<<( ACE_SString & str )
{
	if( initialized() )
	{
		if( error() )
		{
			throw Error();
		}

		char * cp = str.rep();

		mError = 0;

		if( this->send_n(cp,strlen(cp)) == -1 )
		{
			mError = 1;
			throw Error();
		}
	}
	else
	{
		mError = 2;
		throw Error();
	}

	return *this ;
}

Client & Client::operator<< ( char * str )
{
	ACE_SString newStr(str);

	*this << newStr;

	return *this ;
}

Client & Client::operator<< ( int n )
{
	char buf[1024];
	sprintf(buf,"(%d)\n",n);
	ACE_SString newStr(buf);

	*this << newStr;

	return *this;
}

int main (int argc, char *argv[])
{
  const char *server_host = argc > 1 ? argv[1]                : ACE_DEFAULT_SERVER_HOST;
  u_short server_port     = argc > 2 ? ACE_OS::atoi (argv[2]) : ACE_DEFAULT_SERVER_PORT;
  int max_iterations      = argc > 3 ? ACE_OS::atoi (argv[3]) : 4;

  Client server(server_host,server_port);

  if( ! server.initialized() )
  {
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "intialization"), -1);
  }

  
  for (int i = 0; i < max_iterations; i++)
    {
      try
      {
      	server << "message = " << i+1;
        ACE_OS::sleep (1);
      }
      catch ( Client::Error & e )
      {
	cout << "There was an error sending the data\n";
      }
    }

  if (server.close () == -1)
  {
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "close"), -1);
  }

  return 0;
}