forked from zid/Diablo-MUD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.c
83 lines (67 loc) · 1.37 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
#include <stdlib.h>
#include <unistd.h>
#include "socket.h"
#include "client.h"
#include "server.h"
#include "init.h"
struct server {
int socket;
int maxfd;
fd_set readfds;
};
server *server_new(int port)
{
server *s;
s = malloc(sizeof(server));
s->socket = socket_listen_new(port);
s->maxfd = s->socket;
FD_ZERO(&s->readfds);
FD_SET(s->socket, &s->readfds);
init_all();
return s;
}
int server_do(server *s)
{
fd_set readfds;
int i;
/* s->readfds is an accurate list of all our
* clients currently connected. Copy it here
* and then we can act on every client.
*/
readfds = s->readfds;
select(s->maxfd + 1, &readfds, NULL, NULL, NULL);
/* Check for file descriptors that need reading
* and pass them off to client_handle if they do.
*/
for(i = 0; i <= s->maxfd; i++)
{
if(!FD_ISSET(i, &readfds))
continue;
/* The server's socket needing reading
* is special, it means a new client has
* connected so handle it seperately.
*/
if(i == s->socket)
{
int newfd;
newfd = client_init(s->socket);
if(!newfd)
continue;
FD_SET(newfd, &s->readfds);
if(newfd > s->maxfd)
s->maxfd = newfd;
} else {
int r;
/* If r is 0, then the client disconnected. */
r = client_handle(i);
if(!r)
FD_CLR(i, &s->readfds);
}
}
return 1;
}
void server_destroy(server *s)
{
socket_close(s->socket);
free(s);
}