1 #include "otsdaq/NetworkUtilities/TCPReceiverSocket.h"
3 #include <sys/socket.h>
9 #include "otsdaq/Macros/CoutMacros.h"
14 TCPReceiverSocket::TCPReceiverSocket(
int socketId) :
TCPSocket(socketId) {}
17 TCPReceiverSocket::~TCPReceiverSocket(
void) {}
20 std::string TCPReceiverSocket::receivePacket(std::chrono::milliseconds timeout)
22 std::string retVal =
"";
23 auto start = std::chrono::steady_clock::now();
25 size_t received_bytes = 0;
26 uint32_t message_size;
27 while(received_bytes < 4 && std::chrono::duration_cast<std::chrono::milliseconds>(
28 std::chrono::steady_clock::now() - start) < timeout)
30 int this_received_bytes =
receive(
31 reinterpret_cast<char*
>(&message_size) + received_bytes, 4 - received_bytes);
32 if(this_received_bytes < 0)
36 received_bytes += this_received_bytes;
39 if(received_bytes == 0 && std::chrono::duration_cast<std::chrono::milliseconds>(
40 std::chrono::steady_clock::now() - start) >= timeout)
48 while(received_bytes < 4)
50 int this_received_bytes =
51 receive(
reinterpret_cast<char*
>(&message_size) + received_bytes,
53 if(this_received_bytes < 0)
57 received_bytes += this_received_bytes;
61 message_size = ntohl(message_size);
64 std::vector<char> buffer(message_size);
66 while(received_bytes < message_size)
68 int this_received_bytes =
69 receive(&buffer[received_bytes], message_size - received_bytes);
71 if(this_received_bytes < 0)
75 received_bytes += this_received_bytes;
78 retVal = std::string(buffer.begin(), buffer.end());
85 std::size_t bufferSize,
89 if(getSocketId() == 0)
91 throw std::logic_error(
"Bad socket object (this object was moved)");
94 int dataRead = ::read(getSocketId(), buffer, bufferSize);
102 ss <<
"Socket file descriptor " << getSocketId()
103 <<
" is not a valid file descriptor or is not open for reading...Errno: "
107 ss <<
"Buffer is outside your accessible address space...Errno: " << errno;
110 ss <<
"Read critical error caused by a programming bug...Errno: " << errno;
116 ss <<
"The call was interrupted by a signal before any data was "
131 ss <<
"Read: returned -1...Errno: " << errno;
135 else if(dataRead ==
static_cast<std::size_t
>(0))
137 __SS__ <<
"Connection closed!" << std::endl;
145 void TCPReceiverSocket::setReceiveTimeout(
unsigned int timeoutSeconds,
146 unsigned int timeoutMicroSeconds)
149 tv.tv_sec = timeoutSeconds;
150 tv.tv_usec = timeoutMicroSeconds;
151 setsockopt(getSocketId(), SOL_SOCKET, SO_RCVTIMEO, (
const char*)&tv,
sizeof tv);