read/write fixed to take a delimiting newline character

This commit is contained in:
2025-10-25 14:12:28 -05:00
parent 6720d725c2
commit af82bf16f2
2 changed files with 39 additions and 9 deletions

View File

@@ -50,9 +50,11 @@ void handle_client(int client_socket){
void start_http_server(std::uint16_t port){
spdlog::info("Starting HTTP server on {}", port);
httplib::Server server = httplib::Server{};
server.Get("/test", [](const httplib::Request &, httplib::Response &res) {
server.Get("/test", [](const httplib::Request& req, httplib::Response &res) {
res.set_content("Hello World!", "text/plain");
spdlog::info("/test endpoint hit by: {}", req.remote_addr);
});
server.listen("0.0.0.0", port);
}
}

View File

@@ -1,12 +1,19 @@
#include <vector>
#include <sys/socket.h>
#include <algorithm>
#include <algorithm>
#include <unistd.h>
#include "socket-utils.hpp"
namespace socket_utils {
ssize_t write_to_socket(int sock_fd, std::vector<char>& write_buffer) {
ssize_t write_to_socket(int sock_fd, std::vector<char>& write_buffer) {
if (write_buffer.empty()) return 0;
// ensure newline termination
if (write_buffer.back() != '\n') {
write_buffer.push_back('\n');
}
char temp[4096];
size_t to_write = std::min(write_buffer.size(), sizeof(temp));
std::copy(write_buffer.begin(), write_buffer.begin() + to_write, temp);
@@ -17,13 +24,34 @@ namespace socket_utils {
}
return bytes_sent;
}
ssize_t read_from_socket(int sock_fd, std::vector<char>& read_buffer) {
char temp[4096]; // local buffer, destroyed when function exits
ssize_t bytes_read = recv(sock_fd, temp, sizeof(temp), 0);
if (bytes_read > 0) {
char temp[4096];
ssize_t total_read = 0;
// Keep reading until newline found
while (true) {
ssize_t bytes_read = recv(sock_fd, temp, sizeof(temp), 0);
if (bytes_read <= 0) {
return (total_read > 0) ? total_read : bytes_read; // error or closed
}
read_buffer.insert(read_buffer.end(), temp, temp + bytes_read);
total_read += bytes_read;
// check for newline in the newly extended buffer
for (size_t i = (read_buffer.size() > static_cast<size_t>(bytes_read)
? read_buffer.size() - bytes_read
: 0);
i < read_buffer.size(); ++i)
{
if (read_buffer[i] == '\n') {
return total_read; // stop when newline is received
}
}
}
return bytes_read;
}
}
} // namespace socket_utils