Files
ft_irc/Server/Server.cpp

99 lines
2.7 KiB
C++

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Server.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: iherman- <iherman-@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/05/06 17:19:12 by iherman- #+# #+# */
/* Updated: 2026/05/07 14:08:48 by iherman- ### ########.fr */
/* */
/* ************************************************************************** */
#include "Server.hpp"
const int Server::kConnectionQueueLimit = 10;
Server::Server() :
port_(PORT_DEFAULT),
password_("")
{
// std::cout << "Hello from server" << std::endl;
}
Server::Server(int port, const std::string& password) :
port_(port),
password_(password)
{
if (port_ < 1 || port_ > 65535)
throw std::runtime_error("Invalid port");
if (password_.empty())
throw std::runtime_error("Empty password");
serverSocket_ = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket_ < 0)
throw std::runtime_error("Failed to create socket");
struct sockaddr_in addr;
std::memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port_);
addr.sin_addr.s_addr = INADDR_ANY;
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_
<< std::endl;
}
Server::~Server()
{
close(serverSocket_);
}
Server &Server::operator=(const Server& other)
{
if (this != &other)
{
port_ = other.port_;
serverSocket_ = other.serverSocket_;
password_ = other.password_;
}
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 = sizeof(client_addr);
int clientSocket = accept(serverSocket_, (struct sockaddr*)&client_addr, &client_addr_size);
std::string message;
while (true)
{
int recv_amount = recv(clientSocket, buffer, kBufferSize, 0);
if (recv_amount <= 0)
break ;
message.append(buffer, recv_amount);
if (message.find('\n') != std::string::npos)
break ;
}
message = "Server received: " + message;
send(clientSocket, message.c_str(), message.size(), 0);
close(clientSocket);
}