]> git.lizzy.rs Git - dragonblocks_alpha.git/blob - src/network.c
f4fb0a50896d7b528c9dad2e815e7ea7874667f2
[dragonblocks_alpha.git] / src / network.c
1 #include <poll.h>
2
3 bool send_command(Client *client, RemoteCommand cmd)
4 {
5         pthread_mutex_lock(&client->mtx);
6         bool ret = write_u32(client->fd, cmd);
7         pthread_mutex_unlock(&client->mtx);
8         return ret;
9 }
10
11 static bool handle_packets(Client *client) {
12         while (client->state != CS_DISCONNECTED || ! interrupted) {
13                 struct pollfd pfd = {
14                         .fd = client->fd,
15                         .events = POLLIN,
16                         .revents = 0,
17                 };
18
19                 int pstate = poll(&pfd, 1, 0);
20
21                 if (pstate == -1) {
22                         perror("poll");
23                         break;
24                 }
25
26                 if (pstate == 0) {
27                         sched_yield();
28                         continue;
29                 }
30
31                 if (! (pfd.revents & POLLIN))
32                         return false;
33
34                 HostCommand command;
35                 if (! read_u32(client->fd, &command))
36                         break;
37
38                 CommandHandler *handler = NULL;
39
40                 if (command < HOST_COMMAND_COUNT)
41                         handler = &command_handlers[command];
42
43                 if (handler && handler->func) {
44                         bool good = client->state & handler->state_flags;
45                         if (! good)
46                                 printf("Received %s command, but client is in invalid state: %d\n", handler->name, client->state);
47                         if (! handler->func(client, good))
48                                 break;
49                 } else {
50                         printf("Received invalid command %d\n", command);
51                 }
52         }
53
54         return client->state == CS_DISCONNECTED || errno == EINTR;
55 }