Zappy - Year end project 2
This is a project that Epitech asked us to create in order to allow us to reveiw the notions of the current year.
Loading...
Searching...
No Matches
server_loop.c
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2024
3** server
4** File description:
5** server_loop
6*/
7
8#include <arpa/inet.h>
9#include <stdio.h>
10
11#include "utils.h"
12#include "constants.h"
13#include "server_handler.h"
14
15static void add_in_fd_queue(server_handler_t *server, const int fd)
16{
17 for (int i = 0; i < MAX_CLIENT; i++) {
18 if (server->fd_queue[i] == UNKNOWN) {
19 server->fd_queue[i] = fd;
20 break;
21 }
22 }
23}
24
25static int connection_handling(server_handler_t *server, const int i)
26{
27 struct sockaddr_in addr;
28 socklen_t len = sizeof(addr);
29 int client_fd = 0;
30
31 if (i == server->socket) {
32 client_fd = accept(server->socket, (struct sockaddr *)&addr, &len);
33 if (client_fd == -1) {
35 }
36 FD_SET(client_fd, &server->current_fd);
37 write_to_client(client_fd, "WELCOME\n");
38 add_in_fd_queue(server, client_fd);
39 printf("Connexion from %s:%d\n", inet_ntoa(addr.sin_addr),
40 ntohs(addr.sin_port));
41 return (0);
42 }
43 command_handling(server, i);
44 return (0);
45}
46
47static int fd_loop_statement(server_handler_t *server, const int i)
48{
49 if (FD_ISSET(i, &server->ready_fd)) {
50 if (connection_handling(server, i) == -1) {
51 return (-1);
52 }
53 }
54 return (0);
55}
56
57static int loop_in_fd(server_handler_t *server)
58{
59 for (int i = 0; i < FD_SETSIZE; i++) {
60 if (fd_loop_statement(server, i) == -1) {
61 return (-1);
62 }
63 }
64 return (0);
65}
66
68{
69 FD_ZERO(&server->current_fd);
70 FD_SET(server->socket, &server->current_fd);
71 while (true) {
72 server->ready_fd = server->current_fd;
73 if (select(FD_SETSIZE, &server->ready_fd, NULL, NULL, NULL) == -1) {
74 break;
75 }
76 if (loop_in_fd(server) == -1) {
77 break;
78 }
79 }
80}
#define CONNEXION_FAILED
! MESSAGE !!
Definition constants.h:62
#define MAX_CLIENT
Definition constants.h:15
#define UNKNOWN
Definition constants.h:16
void command_handling(server_handler_t *server, const int fd)
Handle client message/command.
void server_loop(server_handler_t *server)
The server loop where communication client/server can be done.
Definition server_loop.c:67
A structure to store server general data.
int fd_queue[MAX_CLIENT]
int write_to_client(const int fd, const char *str)
Write any message to a specific file descriptor.
Definition writer.c:17
int write_error_msg(const char *str)
! WRITTER !!
Definition writer.c:11