@@ -66,23 +66,36 @@ class Client : public Manageable {
6666
6767 // Establish first available connection.
6868 struct addrinfo *currentHost;
69- for (currentHost = results; currentHost != NULL ; currentHost = currentHost->ai_next ) {
70- if ((socketHandle = socket (currentHost->ai_family ,
71- currentHost->ai_socktype , currentHost->ai_protocol )) == -1 ) {
72- continue ;
73- }
74-
75- if (connect (socketHandle, currentHost->ai_addr , currentHost->ai_addrlen ) == 0 ) {
76- std::cout << " [Client] Connected to " << serverName << " :" << serverPort << std::endl;
77- break ;
78- }
79-
80- ::close (socketHandle);
69+ bool connected = false ;
70+
71+ for (int ii=0 ; ii<retryLimit; ++ii) {
72+ for (currentHost = results; currentHost != NULL ; currentHost = currentHost->ai_next ) {
73+ if ((socketHandle = socket (currentHost->ai_family ,
74+ currentHost->ai_socktype , currentHost->ai_protocol )) == -1 ) {
75+ continue ;
76+ }
77+
78+ if (connect (socketHandle, currentHost->ai_addr , currentHost->ai_addrlen ) == 0 ) {
79+ std::cout << " [Client] Connected to " << serverName << " :" << serverPort << std::endl;
80+ connected = true ;
81+ break ;
82+ }
83+
84+ ::close (socketHandle);
85+
86+ }
87+
88+ if (connected) {
89+ break ;
90+ } else {
91+ std::cout << " [Client] Connection failed - attempting reconnect to " << serverName << " :" << serverPort << std::endl;
92+ sleep (1 );
93+ }
8194 }
8295
8396 freeaddrinfo (results);
8497
85- if (currentHost == NULL ) {
98+ if (not connected ) {
8699 stream.str (" " );
87100 stream << " Failed to connect to " << serverName << " :" << serverPort;
88101 throw IOException (stream.str ());
@@ -114,6 +127,15 @@ class Client : public Manageable {
114127 Manageable::close ();
115128 }
116129
130+ /* *
131+ * sets the retry limit for initial connection
132+ *
133+ * @param limit @copydoc retryLimit
134+ */
135+ void setRetryLimit (const int limit) {
136+ retryLimit = limit;
137+ }
138+
117139 /* *
118140 * sets the host to which this instance will attempt to connect the next
119141 * time open() is called
@@ -150,7 +172,8 @@ class Client : public Manageable {
150172 Client (const T& commandSource, const std::string& host, unsigned short port) :
151173 source (commandSource),
152174 serverName (host),
153- serverPort (port) {}
175+ serverPort (port),
176+ retryLimit (5 ) {}
154177
155178 /* *
156179 * packs commands from @a source into @a commands
@@ -178,6 +201,9 @@ class Client : public Manageable {
178201 /* * the port on which the server is listening */
179202 unsigned short serverPort;
180203
204+ /* * Number of times to retry establishing the initial connection */
205+ int retryLimit;
206+
181207 /* * the socket */
182208 int socketHandle;
183209
0 commit comments