1
+ #include "poll_n_server.h"
2
+ #include <stdio.h>
3
+ #include <stdlib.h>
4
+ #include "poll.h"
5
+ #include <sys/socket.h>
6
+ #include <netinet/in.h>
7
+
8
+
9
+ int main (int argc , char * argv [])
10
+ {
11
+ if (argc < 2 ){
12
+ printf ("Usage: %s N\n" , argv [0 ]);
13
+ exit (EXIT_FAILURE );
14
+ }
15
+
16
+ int num_of_clients = atoi (argv [1 ]);
17
+
18
+ struct sockaddr_in client_addr , server_addr ;
19
+
20
+ int listen_sockfd , conn_sockfd , client_sockfd ;
21
+
22
+ struct pollfd poll_fds [num_of_clients + 1 ]; // 1 for listen_sockfd
23
+
24
+ int curr_cli_count = 0 ;
25
+
26
+ for (int i = 0 ; i < num_of_clients ; i ++ ){
27
+ poll_fds [i ].fd = -1 ;
28
+ poll_fds [i ].events = POLLIN ;
29
+ }
30
+
31
+ poll_fds [num_of_clients ].fd = listen_sockfd ;
32
+ poll_fds [num_of_clients ].events = POLLIN ;
33
+
34
+ listen_sockfd = socket (AF_INET , SOCK_STREAM , 0 );
35
+ bzero (& server_addr , sizeof (struct sockaddr_in ));
36
+
37
+ server_addr .sin_family = AF_INET ;
38
+ server_addr .sin_port = htons (SERVER_PORT );
39
+ server_addr .sin_addr .s_addr = inet_addr ("127.0.0.1" );
40
+
41
+ bind (listen_sockfd , (struct sockaddr * )& server_addr , sizeof (server_addr ));
42
+ listen (listen_sockfd , MAX_QUEUE_SIZE );
43
+
44
+ int poll_status ;
45
+ int num_ready = 0 ;
46
+
47
+ for ( ; ; ){
48
+ poll_status = poll (poll_fds , num_of_clients , TIMEOUT_MS );
49
+
50
+ if (poll_status == -1 ){
51
+ perror ("poll" );
52
+ exit (EXIT_FAILURE );
53
+ }
54
+
55
+ if (poll_status == 0 ){
56
+ printf ("Timeout occured\n" );
57
+ return 0 ;
58
+ }
59
+
60
+ num_ready = poll_status ;
61
+
62
+ if (poll_fds [num_of_clients ].revents & POLLIN ) // listening socket is readable
63
+ conn_sockfd = accept (listen_sockfd , (struct sockaddr * )& client_addr , sizeof (client_addr ));
64
+
65
+ int i ;
66
+
67
+ for (i = 0 ; i < num_of_clients ; i ++ ){
68
+ if (poll_fds [i ].fd == -1 ){
69
+ poll_fds [i ].fd = conn_sockfd ;
70
+ break ;
71
+ }
72
+ }
73
+
74
+ if (i == num_of_clients ){
75
+ printf ("Number of clients exceeded %d\n" , num_of_clients );
76
+ exit (EXIT_FAILURE );
77
+ }
78
+
79
+ if (-- num_ready <= 0 ){
80
+ continue ; // no more readable clients
81
+ }
82
+
83
+ for (i = 0 ; i < num_of_clients ; i ++ ){
84
+ if (poll_fds [i ].revents & POLLIN ){
85
+ // send data to all other clients
86
+ for (int j = 0 ; j < num_of_clients ; j ++ ){
87
+ if (j != i ){
88
+ // send(poll_fds[i].fd,)
89
+ }
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ return 0 ;
96
+ }
0 commit comments