23 #include <arpa/inet.h> 25 #include <netinet/tcp.h> 49 setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &flag,
sizeof(
int));
50 setsockopt(socket_fd, IPPROTO_TCP, TCP_QUICKACK, &flag,
sizeof(
int));
54 setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO,
recv_timeout_.get(),
sizeof(timeval));
63 URCL_LOG_DEBUG(
"Setting up connection: %s:%d", host.c_str(), port);
68 const char* host_name = host.empty() ? nullptr : host.c_str();
69 std::string service = std::to_string(port);
70 struct addrinfo hints, *result;
71 std::memset(&hints, 0,
sizeof(hints));
73 hints.ai_family = AF_UNSPEC;
74 hints.ai_socktype = SOCK_STREAM;
75 hints.ai_flags = AI_PASSIVE;
77 bool connected =
false;
80 if (getaddrinfo(host_name, service.c_str(), &hints, &result) != 0)
82 URCL_LOG_ERROR(
"Failed to get address for %s:%d", host.c_str(), port);
86 for (
struct addrinfo* p = result; p !=
nullptr; p = p->ai_next)
88 socket_fd_ = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol);
102 std::stringstream ss;
103 ss <<
"Failed to connect to robot on IP " << host_name
104 <<
". Please check that the robot is booted and reachable on " << host_name <<
". Retrying in " 112 URCL_LOG_DEBUG(
"Connection established for %s:%d", host.c_str(), port);
129 socklen_t len =
sizeof(name);
130 int res = ::getsockname(
socket_fd_, (sockaddr*)&name, &len);
135 return std::string();
139 inet_ntop(AF_INET, &name.sin_addr, buf,
sizeof(buf));
140 return std::string(buf);
149 return read((uint8_t*)character, 1, read_chars);
159 ssize_t res = ::recv(
socket_fd_, buf, buf_len, 0);
169 read =
static_cast<size_t>(res);
183 size_t remaining = buf_len;
186 while (written < buf_len)
188 ssize_t sent = ::send(
socket_fd_, buf + written, remaining, 0);
#define URCL_LOG_ERROR(...)
bool write(const uint8_t *buf, const size_t buf_len, size_t &written)
Writes to the socket.
std::atomic< SocketState > state_
Connection to socket got closed.
std::atomic< int > socket_fd_
SocketState
State the socket can be in.
std::unique_ptr< timeval > recv_timeout_
Socket is initialized or setup failed.
Socket is disconnected and cannot be used.
bool read(char *character)
Reads one byte from the socket.
std::string getIP() const
Determines the local IP address of the currently configured socket.
#define URCL_LOG_DEBUG(...)
bool setup(std::string &host, int port)
void close()
Closes the connection to the socket.
Socket is connected and ready to use.
virtual void setOptions(int socket_fd)
virtual bool open(int socket_fd, struct sockaddr *address, size_t address_len)
std::chrono::seconds reconnection_time_
void setReceiveTimeout(const timeval &timeout)
Setup Receive timeout used for this socket.
TCPSocket()
Creates a TCPSocket object.