This repository has been archived by the owner on May 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.c
101 lines (87 loc) · 2.19 KB
/
server.c
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
#include "lib/header.h"
int main(int argc, char *argv[]) {
if(argc != 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
int listen_fd;
int clients[FD_SETSIZE];
int client_maxi = 0;
int max_fd;
memset(clients, 0xFF, sizeof(clients));
struct sockaddr_in listen_addr;
memset(&listen_addr, 0, sizeof(listen_addr));
listen_addr.sin_family = AF_INET;
listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);
listen_addr.sin_port = htons(atoi(argv[1]));
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if(listen_fd == -1) {
fputs("Cannot create socket.\n", stderr);
exit(2);
}
if(bind(listen_fd, (struct sockaddr *) &listen_addr, sizeof(listen_addr)) == -1) {
fputs("Cannot bind.\n", stderr);
exit(2);
}
if(listen(listen_fd, 1024) == -1) {
fputs("Cannot listen.\n", stderr);
exit(2);
}
fd_set all_set, r_set;
FD_SET(listen_fd, &all_set);
max_fd = listen_fd + 1;
while(1) {
r_set = all_set;
int nready = select(max_fd, &r_set, NULL, NULL, NULL);
if(FD_ISSET(listen_fd, &r_set)) {
struct sockaddr_in client_addr;
int client_len = sizeof(client_addr);
int client_fd = accept(listen_fd, (struct sockaddr *) &client_addr, &client_len);
/* boardcast to welcome this client */
#ifdef FLAVOR
boardcast(clients, client_maxi, "\033[33mSomeone is coming!\033[m");
#else
boardcast(clients, client_maxi, "Someone is coming!");
#endif
int i;
for(i=0; i<FD_SETSIZE; i++) {
if(clients[i] < 0) {
clients[i] = client_fd;
break;
}
}
/* hello to this client */
user_init(clients, i, &client_addr);
if(i == FD_SETSIZE) {
printf("Too many clients!\n");
exit(2);
}
if(i > client_maxi) {
client_maxi = i;
}
if(client_fd >= max_fd) {
max_fd = client_fd + 1;
}
FD_SET(client_fd, &all_set);
if(--nready)
continue;
}
int i;
for(i=0; i<=client_maxi && nready; i++) {
if(FD_ISSET(clients[i], &r_set)) {
--nready;
char buf[CMD_MAX];
int n = read(clients[i], buf, 999);
if(n == 0) {
close(clients[i]);
FD_CLR(clients[i], &all_set);
clients[i] = -1;
user_down(clients, client_maxi, i);
} else {
buf[n] = '\0';
proc_cmd(clients, client_maxi, i, buf);
}
}
}
}
}