]> git.lizzy.rs Git - dragonnet.git/blob - recv_thread.c
Add socket (de)serialization generator
[dragonnet.git] / recv_thread.c
1 #include <assert.h>
2 #include <dragontype/number.h>
3 #include <pthread.h>
4 #include <stdbool.h>
5 #include <stdio.h>
6 #include <unistd.h>
7
8 #include "peer.h"
9 #include "recv_thread.h"
10
11 void *dragonnet_peer_recv_thread(void *g_peer)
12 {
13         DragonnetPeer *p = (DragonnetPeer *) g_peer;
14
15         pthread_rwlock_wrlock(&p->mu);
16         assert(p->state == DRAGONNET_PEER_CREATED);
17         p->state++;
18         pthread_rwlock_unlock(&p->mu);
19
20         while (true) {
21                 u16 msg;
22
23                 // Copy socket fd so that shutdown doesn't block
24                 pthread_rwlock_rdlock(&p->mu);
25                 int sock = p->sock;
26                 pthread_rwlock_unlock(&p->mu);
27
28                 ssize_t len = recv(sock, &msg, sizeof msg, MSG_WAITALL);
29
30                 if (len < 0) {
31                         perror("recv");
32                         dragonnet_peer_delete(p);
33                         return NULL;
34                 }
35
36                 // Connection closed
37                 if (len == 0) {
38                         pthread_rwlock_wrlock(&p->mu);
39
40                         close(p->sock);
41                         p->sock = -1;
42                         p->state++;
43
44                         pthread_rwlock_unlock(&p->mu);
45                         return NULL;
46                 }
47
48                 // Deserialization
49         }
50 }