wip client arrived

This commit is contained in:
asus
2023-02-24 12:00:23 +01:00
parent 377ba175c4
commit 3fe27ea14e
2 changed files with 32 additions and 8 deletions

BIN
a.out

Binary file not shown.

View File

@@ -30,7 +30,7 @@
// strstr
// write
#define BUFSIZE 1024
#define BUFSIZE 100
typedef struct s_client {
int fd;
@@ -91,7 +91,7 @@ char *str_join(char *buf, char *add)
return (newbuf);
}
void add_client(t_client *first_client, int fd, int id) {
void add_client(t_client **first_client, int fd, int id) {
t_client *new_client;
t_client *client;
@@ -101,16 +101,35 @@ void add_client(t_client *first_client, int fd, int id) {
new_client->fd = fd;
new_client->id = id;
new_client->next = NULL;
if (!first_client)
first_client = new_client;
if (!(*first_client))
*first_client = new_client;
else {
client = first_client;
client = *first_client;
while (client->next)
client = client->next;
client->next = new_client;
}
}
void broadcast(char *buf, fd_set *set, int maxfd, int client_fd) {
for(int fd = 0; fd <= maxfd; ++fd) {
if (fd == client_fd)
continue;
if (FD_ISSET(fd, set))
send(fd, buf, strlen(buf), 0);
}
}
// debug
void print_clients(t_client *client) {
printf("clients:");
while(client) {
printf("[%i - %i]", client->id, client->fd);
client = client->next;
}
printf("\n");
}
int main(int ac, char **av) {
int sockfd;
int client_fd;
@@ -121,6 +140,7 @@ int main(int ac, char **av) {
fd_set write_set;
t_client *client;
t_client *first_client;
char buf[BUFSIZE];
if (ac != 2)
error("Wrong number of arguments\n");
@@ -146,13 +166,15 @@ int main(int ac, char **av) {
error("Fatal error\n");
while(1) {
print_clients(first_client);
maxfd = sockfd;
FD_ZERO(&read_set);
FD_ZERO(&write_set);
FD_SET(sockfd, &read_set);
client = first_client;
while(client) {
write(1, "1", 1);
printf("id: %i\n", client->id);
//printf("id: %i\n", client->id);
FD_SET(client->fd, &read_set);
FD_SET(client->fd, &write_set);
if (client->fd > maxfd)
@@ -160,11 +182,13 @@ printf("id: %i\n", client->id);
client = client->next;
}
select(maxfd + 1, &read_set, &write_set, NULL, NULL);
select(maxfd + 1, &read_set, NULL, NULL, NULL);
if (FD_ISSET(sockfd, &read_set)) {
client_fd = accept(sockfd, NULL, NULL);
add_client(first_client, client_fd, id);
add_client(&first_client, client_fd, id);
sprintf(buf, "server: client %d just arrived\n", id);
broadcast(buf, &write_set, maxfd, client_fd) {
id++;
}
}