1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
fd_max = sockfd;
while (1)
{
switch (select(fd_max + 1, &readfds, NULL, NULL, NULL))
{
case -1:
{
perror("select");
return EXIT_FAILURE;
}
case 0:
break;
default:
{
int i, j;
// Sent message
// Searching sender
for (i = 0; i < num_clients; i++)
{
if (FD_ISSET(clients[i].sockfd, &readfds))
{
// Getting message
while ((n = recv(clients[i].sockfd, buffer, sizeof(buffer) - 1, 0)) > 0)
{
buffer[n] = '\0';
printf("message recu du client %d : %s", i, buffer);
// Sending this message to others
for (j = 0; j < num_clients; j++)
{
if (i != j)
{
if (send(clients[j].sockfd, buffer, n, 0) == -1)
{
perror("send");
return EXIT_SUCCESS;
}
}
}
// Breaking if message was complete
if (n < sizeof(buffer - 1))
break;
}
// Error during reception
if (n == -1)
{
perror("recv");
close(sockfd);
return EXIT_FAILURE;
}
}
}
// New client
if (FD_ISSET(sockfd, &readfds) && num_clients < MAX_USERS)
{
// Accepting connection
if ((clients[num_clients].sockfd = accept(sockfd, (struct sockaddr *)(&clients[num_clients].addr), &sin_size)) == -1)
{
perror("accept");
close(sockfd);
return EXIT_FAILURE;
}
// Updating fd_set and fd_max
FD_SET(clients[num_clients].sockfd, &readfds);
if (clients[num_clients].sockfd > fd_max)
fd_max = clients[num_clients].sockfd;
printf("Nouvelle connexion : %d\n", clients[num_clients].sockfd);
num_clients++;
}
break;
}
}
} |
Partager