@@ -42,10 +42,11 @@ namespace urcl
4242{
4343namespace comm
4444{
45- TCPServer::TCPServer (const int port) : port_(port), maxfd_(0 ), max_clients_allowed_(0 )
45+ TCPServer::TCPServer (const int port, const size_t max_num_tries, const std::chrono::milliseconds reconnection_time)
46+ : port_(port), maxfd_(0 ), max_clients_allowed_(0 )
4647{
4748 init ();
48- bind ();
49+ bind (max_num_tries, reconnection_time );
4950 startListen ();
5051}
5152
@@ -124,21 +125,38 @@ void TCPServer::shutdown()
124125 }
125126}
126127
127- void TCPServer::bind ()
128+ void TCPServer::bind (const size_t max_num_tries, const std::chrono::milliseconds reconnection_time )
128129{
129130 struct sockaddr_in server_addr;
130131 server_addr.sin_family = AF_INET;
131132
132133 // INADDR_ANY is a special constant that signalizes "ANY IFACE",
133134 server_addr.sin_addr .s_addr = htonl (INADDR_ANY);
134135 server_addr.sin_port = htons (port_);
135- int err = ::bind (listen_fd_, (struct sockaddr *)&server_addr, sizeof (server_addr));
136- if (err == -1 )
136+ int err = -1 ;
137+ size_t connection_counter = 0 ;
138+ do
137139 {
138- std::ostringstream ss;
139- ss << " Failed to bind socket for port " << port_ << " to address. Reason: " << strerror (errno);
140- throw std::system_error (std::error_code (errno, std::generic_category ()), ss.str ());
141- }
140+ err = ::bind (listen_fd_, (struct sockaddr *)&server_addr, sizeof (server_addr));
141+ if (err == -1 )
142+ {
143+ std::ostringstream ss;
144+ ss << " Failed to bind socket for port " << port_ << " to address. Reason: " << strerror (errno);
145+
146+ if (connection_counter++ < max_num_tries || max_num_tries == 0 )
147+ {
148+ std::this_thread::sleep_for (reconnection_time);
149+ ss << " Retrying in " << std::chrono::duration_cast<std::chrono::duration<float >>(reconnection_time).count ()
150+ << " seconds" ;
151+ URCL_LOG_WARN (" %s" , ss.str ().c_str ());
152+ }
153+ else
154+ {
155+ throw std::system_error (std::error_code (errno, std::generic_category ()), ss.str ());
156+ }
157+ }
158+ } while (err == -1 && (connection_counter <= max_num_tries || max_num_tries == 0 ));
159+
142160 URCL_LOG_DEBUG (" Bound %d:%d to FD %d" , server_addr.sin_addr .s_addr , port_, (int )listen_fd_);
143161
144162 FD_SET (listen_fd_, &masterfds_);
0 commit comments