tcp net wip

This commit is contained in:
vaclavt
2022-05-05 18:01:57 +02:00
parent 4dfdd76b05
commit 3695a54e9a
2 changed files with 23 additions and 5 deletions

View File

@@ -71,10 +71,7 @@ int TcpNet::server(int portno, const std::function<std::pair<bool, std::string>(
shutdown = response.first; shutdown = response.first;
std::string response_str = response.second; std::string response_str = response.second;
auto response_len = response_str.size(); write_to_socket(newsockfd, response_str);
auto n = write(newsockfd, response_str.c_str(), response_len);
if (n < 0 || response_len != n)
error("ERROR writing to socket");
requests_processed++; requests_processed++;
} }
@@ -134,10 +131,20 @@ std::string TcpNet::client(const std::string &address, int portno, const std::st
return response[0]; return response[0];
} }
std::string TcpNet::read_from_socket(int sockfd) { std::string TcpNet::read_from_socket(int sockfd) {
char buffer[TCPNET_BUFFER_SIZE]; char buffer[TCPNET_BUFFER_SIZE];
std::string request; 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; long n;
do { do {
memset(buffer, 0, TCPNET_BUFFER_SIZE); memset(buffer, 0, TCPNET_BUFFER_SIZE);
@@ -153,7 +160,7 @@ std::string TcpNet::read_from_socket(int sockfd) {
std::string part{buffer}; std::string part{buffer};
request.append(part); 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; return request;
} }
@@ -162,6 +169,16 @@ void TcpNet::write_to_socket(int sockfd, const std::string &str) {
const char *buffer = str.c_str(); const char *buffer = str.c_str();
int pos = 0; int pos = 0;
long n; 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 { do {
n = write(sockfd, buffer + pos, (int) (str.length() - pos)); n = write(sockfd, buffer + pos, (int) (str.length() - pos));
if (n < 0) if (n < 0)

View File

@@ -17,6 +17,7 @@ public:
[[nodiscard]] std::vector<std::string> client(const std::string &address, int portno, const std::vector<std::string> &requests) const; [[nodiscard]] std::vector<std::string> client(const std::string &address, int portno, const std::vector<std::string> &requests) const;
private: private:
static const bool USE_LENGTH_HEADER = true;
static std::string read_from_socket(int sockfd) ; static std::string read_from_socket(int sockfd) ;
static void write_to_socket(int sockfd, const std::string &str) ; static void write_to_socket(int sockfd, const std::string &str) ;
}; };