diff --git a/clib/tcpnet.cpp b/clib/tcpnet.cpp index 2afbe14..b14c2e7 100644 --- a/clib/tcpnet.cpp +++ b/clib/tcpnet.cpp @@ -71,10 +71,7 @@ int TcpNet::server(int portno, const std::function( shutdown = response.first; std::string response_str = response.second; - auto response_len = response_str.size(); - auto n = write(newsockfd, response_str.c_str(), response_len); - if (n < 0 || response_len != n) - error("ERROR writing to socket"); + write_to_socket(newsockfd, response_str); requests_processed++; } @@ -134,10 +131,20 @@ std::string TcpNet::client(const std::string &address, int portno, const std::st return response[0]; } + std::string TcpNet::read_from_socket(int sockfd) { char buffer[TCPNET_BUFFER_SIZE]; std::string request; + // read length header + unsigned long long bytesLen = 0; + if (USE_LENGTH_HEADER) { + long n = read(sockfd, &bytesLen, sizeof(bytesLen)); + if (n != 0 && n != sizeof(bytesLen)) + error("ERROR reading length header failed"); + } + + // read data long n; do { memset(buffer, 0, TCPNET_BUFFER_SIZE); @@ -153,7 +160,7 @@ std::string TcpNet::read_from_socket(int sockfd) { std::string part{buffer}; request.append(part); - } while (n == TCPNET_BUFFER_SIZE - 1); // TODO what if data exactly of this size + } while ((USE_LENGTH_HEADER && n < bytesLen) || n == TCPNET_BUFFER_SIZE - 1); // TODO what if data exactly of this size return request; } @@ -162,6 +169,16 @@ void TcpNet::write_to_socket(int sockfd, const std::string &str) { const char *buffer = str.c_str(); int pos = 0; long n; + + // write length header + unsigned long long bytesLen = str.length(); + if (USE_LENGTH_HEADER) { + n = write(sockfd, &bytesLen, (int) sizeof(bytesLen)); + if (n < 0) + error("ERROR writing size number to socket"); + } + + // write data do { n = write(sockfd, buffer + pos, (int) (str.length() - pos)); if (n < 0) diff --git a/clib/tcpnet.h b/clib/tcpnet.h index 4adab26..f153d27 100644 --- a/clib/tcpnet.h +++ b/clib/tcpnet.h @@ -17,6 +17,7 @@ public: [[nodiscard]] std::vector client(const std::string &address, int portno, const std::vector &requests) const; private: + static const bool USE_LENGTH_HEADER = true; static std::string read_from_socket(int sockfd) ; static void write_to_socket(int sockfd, const std::string &str) ; };