training
This commit is contained in:
16
mini_serv.c
16
mini_serv.c
@@ -8,7 +8,7 @@
|
||||
#include <stdio.h>
|
||||
|
||||
#define MSGSIZE 1024
|
||||
#define BUFSIZE MSGSIZE + 120000
|
||||
#define BUFSIZE 120000
|
||||
|
||||
typedef struct s_client {
|
||||
int id;
|
||||
@@ -20,10 +20,8 @@ void error(char *msg) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
void broadcast(char *msg, fd_set *set, int max_fd, int server_fd, int current_fd) {
|
||||
void broadcast(char *msg, fd_set *set, int max_fd, int current_fd) {
|
||||
for(int i = 0; i <= max_fd; ++i) {
|
||||
if (i == server_fd)
|
||||
continue;
|
||||
if (i == current_fd)
|
||||
continue;
|
||||
if (FD_ISSET(i, set))
|
||||
@@ -44,6 +42,7 @@ int main(int ac, char **av) {
|
||||
socklen_t addr_len;
|
||||
fd_set fdset;
|
||||
fd_set rdset;
|
||||
fd_set wdset;
|
||||
t_client clients[FD_SETSIZE];
|
||||
|
||||
if (ac != 2)
|
||||
@@ -76,8 +75,9 @@ int main(int ac, char **av) {
|
||||
|
||||
while(1) {
|
||||
rdset = fdset;
|
||||
wdset = fdset;
|
||||
|
||||
select(max_fd + 1, &rdset, NULL, NULL, NULL);
|
||||
select(max_fd + 1, &rdset, &wdset, NULL, NULL);
|
||||
|
||||
if (FD_ISSET(server_fd, &rdset)) {
|
||||
client_fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
|
||||
@@ -87,7 +87,7 @@ int main(int ac, char **av) {
|
||||
clients[client_fd].id = id;
|
||||
bzero(clients[client_fd].msg, MSGSIZE);
|
||||
sprintf(msg, "server: client %d just arrived\n", id);
|
||||
broadcast(msg, &fdset, max_fd, server_fd, client_fd);
|
||||
broadcast(msg, &wdset, max_fd, client_fd);
|
||||
id++;
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ int main(int ac, char **av) {
|
||||
ret = recv(client_fd, buf, BUFSIZE, 0);
|
||||
if (ret == 0) {
|
||||
sprintf(msg, "server: client %d just left\n", clients[client_fd].id);
|
||||
broadcast(msg, &fdset, max_fd, server_fd, client_fd);
|
||||
broadcast(msg, &wdset, max_fd, client_fd);
|
||||
FD_CLR(client_fd, &fdset);
|
||||
close(client_fd);
|
||||
if (client_fd == max_fd) {
|
||||
@@ -113,7 +113,7 @@ int main(int ac, char **av) {
|
||||
if (buf[i] == '\n') {
|
||||
clients[client_fd].msg[j] = '\0';
|
||||
sprintf(msg, "client %d: %s\n", clients[client_fd].id, clients[client_fd].msg);
|
||||
broadcast(msg, &fdset, max_fd, server_fd, client_fd);
|
||||
broadcast(msg, &wdset, max_fd, client_fd);
|
||||
bzero(clients[client_fd].msg, MSGSIZE);
|
||||
j = -1;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user