@@ -55,7 +55,7 @@ void TCPSocket::setOptions(int socket_fd)
5555 }
5656}
5757
58- bool TCPSocket::setup (std::string& host, int port)
58+ bool TCPSocket::setup (std::string& host, int port, size_t max_num_tries )
5959{
6060 if (state_ == SocketState::Connected)
6161 return false ;
@@ -74,6 +74,7 @@ bool TCPSocket::setup(std::string& host, int port)
7474 hints.ai_socktype = SOCK_STREAM;
7575 hints.ai_flags = AI_PASSIVE;
7676
77+ size_t connect_counter = 0 ;
7778 bool connected = false ;
7879 while (!connected)
7980 {
@@ -96,13 +97,23 @@ bool TCPSocket::setup(std::string& host, int port)
9697
9798 freeaddrinfo (result);
9899
100+ if (max_num_tries > 0 )
101+ {
102+ if (connect_counter++ >= max_num_tries)
103+ {
104+ URCL_LOG_ERROR (" Failed to establish connection for %s:%d after %d tries" , host.c_str (), port, max_num_tries);
105+ state_ = SocketState::Invalid;
106+ return false ;
107+ }
108+ }
109+
99110 if (!connected)
100111 {
101112 state_ = SocketState::Invalid;
102113 std::stringstream ss;
103114 ss << " Failed to connect to robot on IP " << host_name
104115 << " . Please check that the robot is booted and reachable on " << host_name << " . Retrying in "
105- << reconnection_time_.count () << " seconds" ;
116+ << std::chrono::duration_cast<std::chrono::duration< float >>( reconnection_time_) .count () << " seconds" ;
106117 URCL_LOG_ERROR (" %s" , ss.str ().c_str ());
107118 std::this_thread::sleep_for (reconnection_time_);
108119 }
0 commit comments