Added a basic Server::run function which listens for one connection and sends the data back, added listen call to server constructor

This commit is contained in:
iherman-
2026-05-07 13:52:42 +02:00
parent 0c29c50e23
commit 4beabead01
3 changed files with 32 additions and 6 deletions

View File

@@ -6,7 +6,7 @@
/* By: iherman- <iherman-@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/05/06 17:19:12 by iherman- #+# #+# */
/* Updated: 2026/05/07 13:00:56 by iherman- ### ########.fr */
/* Updated: 2026/05/07 13:49:56 by iherman- ### ########.fr */
/* */
/* ************************************************************************** */
@@ -42,7 +42,11 @@ Server::Server(int port, const std::string& password) :
addr.sin_port = htons(port_);
addr.sin_addr.s_addr = INADDR_ANY;
bind(serverSocket_, (struct sockaddr*)&addr, sizeof(addr));
if (bind(serverSocket_, (struct sockaddr*)&addr, sizeof(addr)))
throw std::runtime_error("Failed to bind");
if (listen(serverSocket_, kConnectionQueueLimit))
throw std::runtime_error("Failed to listen");
std::cout << "Server port: " << port_
<< "\nServer Password: " << password_
@@ -65,3 +69,26 @@ Server &Server::operator=(const Server& other)
return *this;
}
void Server::run()
{
const std::size_t kBufferSize = 1024;
char buffer[kBufferSize] = {0};
struct sockaddr_in client_addr;
socklen_t client_addr_size = 0;
int clientSocket = accept(serverSocket_, (struct sockaddr*)&client_addr, &client_addr_size);
std::size_t recv_amount = 0;
while (true)
{
recv_amount += recv(clientSocket, buffer, kBufferSize, 0);
if (buffer[recv_amount - 1] == '\n')
break ;
}
std::string to_send(buffer);
to_send = "Server received: " + to_send;
send(clientSocket, to_send.c_str(), to_send.size(), 0);
close(clientSocket);
}

View File

@@ -6,7 +6,7 @@
/* By: iherman- <iherman-@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/05/06 17:18:11 by iherman- #+# #+# */
/* Updated: 2026/05/07 13:00:39 by iherman- ### ########.fr */
/* Updated: 2026/05/07 13:29:00 by iherman- ### ########.fr */
/* */
/* ************************************************************************** */