implemented processing of incoming client connection

This commit is contained in:
bettercallous
2024-04-09 00:31:39 +00:00
parent c315be1dcd
commit 4c1b396154
6 changed files with 48 additions and 3 deletions

7
Client.cpp Normal file
View File

@@ -0,0 +1,7 @@
#include "Client.hpp"
Client::Client() {}
Client::Client(int fd, std::string addr) : _fd(fd), _addr(addr) {}
Client::~Client() {}

17
Client.hpp Normal file
View File

@@ -0,0 +1,17 @@
#ifndef CLIENT_HPP
#define CLIENT_HPP
#include <iostream>
class Client {
private:
int _fd;
std::string _addr;
public:
Client();
Client(int fd, std::string addr);
~Client();
};
#endif

View File

@@ -1,6 +1,6 @@
NAME = ircserv
SRC = main.cpp Server.cpp
SRC = main.cpp Server.cpp Client.cpp
OBJ = ${SRC:.cpp=.o}

View File

@@ -48,8 +48,7 @@ void Server::run() {
for (size_t i = 0; i < _fds.size(); ++i) {
if (_fds[i].revents & POLLIN) {
if (_fds[i].fd == _serverSocketFd)
// handle new client connection here
continue;
handleClientConnection();
else
// handle existing client incoming data here
continue;
@@ -95,3 +94,21 @@ void Server::addPollfd(int fd, short events, short revents) {
newPollfd.revents = revents;
_fds.push_back(newPollfd);
}
void Server::handleClientConnection() {
for (size_t i = 0; i < _fds.size(); ++i) {
if (_fds[i].fd == _serverSocketFd && (_fds[i].revents & POLLIN)) {
struct sockaddr_in client_addr;
socklen_t clientAddrSize = sizeof(sockaddr_in);
int newFd = accept(_serverSocketFd, (struct sockaddr *)&client_addr, &clientAddrSize);
if (newFd == -1) {
throw std::runtime_error("Error: accept() failed");
}
addPollfd(newFd, POLLIN, 0);
_clients.push_back(Client(newFd, inet_ntoa((client_addr.sin_addr))));
std::cout << "Client <" << newFd << "> Connected" << std::endl;
}
}
}

View File

@@ -8,6 +8,7 @@
#include <fcntl.h>
#include <vector>
#include <poll.h>
#include "Client.hpp"
class Server {
private:
@@ -16,6 +17,7 @@ class Server {
static bool _signal;
std::string _password;
std::vector<struct pollfd> _fds;
std::vector<Client> _clients;
public:
Server();
~Server();
@@ -28,6 +30,7 @@ class Server {
void createServerSocket();
void bindServerSocket();
void addPollfd(int fd, short events, short revents);
void handleClientConnection();
};
#endif

View File

@@ -12,5 +12,6 @@ int main(int ac, char **av)
std::cerr << e.what() << std::endl;
return 1;
}
std::cout << ">>> SERVER CLOSED <<<" << std::endl;
return 0;
}