1 #include "otsdaq/NetworkUtilities/TCPClientBase.h"
5 #include <netinet/in.h>
7 #include <boost/regex.hpp>
14 TCPClientBase::TCPClientBase(
const std::string& serverIP,
int serverPort) : fServerIP(serverIP), fServerPort(serverPort), fConnected(false) {}
17 TCPClientBase::~TCPClientBase(
void)
19 std::cout << __PRETTY_FUNCTION__ <<
"Closing TCPSocket #" << getSocketId() << std::endl;
22 std::cout << __PRETTY_FUNCTION__ <<
"TCPSocket #" << getSocketId() <<
" closed." << std::endl;
26 bool TCPClientBase::connect(
int retry,
unsigned int sleepMilliSeconds)
30 std::cout << __PRETTY_FUNCTION__ <<
"I am already connected...what is going on?" << std::endl;
31 throw std::runtime_error(std::string(
"I am already connected...what is going on?"));
35 std::cout << __PRETTY_FUNCTION__ <<
"Connecting Client socket to server name-" << fServerIP <<
"-serverPort: " << fServerPort << std::endl;
36 std::string serverName = fServerIP;
37 resolveServer(fServerIP);
38 std::cout << __PRETTY_FUNCTION__ <<
"Connecting Client socket to server ip -" << fServerIP <<
"-serverPort: " << fServerPort << std::endl;
39 int status = invalidSocketId;
40 struct sockaddr_in serverSocketAddress;
41 serverSocketAddress.sin_family = AF_INET;
42 serverSocketAddress.sin_port = htons(fServerPort);
43 serverSocketAddress.sin_addr.s_addr = inet_addr(fServerIP.c_str());
45 while(!fConnected && (
unsigned int)retry-- > 0)
49 status = ::connect(getSocketId(), (
struct sockaddr*)&serverSocketAddress,
sizeof(serverSocketAddress));
53 if((
unsigned int)retry > 0)
55 std::cout << __PRETTY_FUNCTION__ <<
"WARNING: Can't connect to " << serverName <<
". The server might still be down...Sleeping "
56 << sleepMilliSeconds <<
"ms and then retry " << (
unsigned int)retry <<
" more times." << std::endl;
57 std::this_thread::sleep_for(std::chrono::milliseconds(sleepMilliSeconds));
62 std::cout << __PRETTY_FUNCTION__ <<
"ERROR: Can't connect to " << serverName <<
" aborting!" << std::endl;
92 std::cout << __PRETTY_FUNCTION__ <<
"Succesfully connected to server " << fServerIP <<
" port: " << fServerPort << std::endl;
99 bool TCPClientBase::disconnect(
void)
103 TCPSocket::sendClose();
112 void TCPClientBase::resolveServer(std::string& serverIP)
114 const std::string ipv4(
115 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
116 "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
117 "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
118 "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
119 boost::regex ip_regex(ipv4.c_str());
122 if(boost::regex_match(serverIP, ip_regex))
124 else if(serverIP ==
"localhost" || serverIP ==
"localhost.localdomain")
126 serverIP =
"127.0.0.1";
130 struct hostent* resolvedHost = ::gethostbyname(serverIP.c_str());
131 if(resolvedHost == NULL)
133 throw std::runtime_error(serverIP +
" is unavailable and can't be resolved!");
136 in_addr* address = (in_addr*)resolvedHost->h_addr;
137 serverIP = inet_ntoa(*address);
138 std::cout <<
"IP: (" << serverIP <<
")\n";