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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
#include "netcode.h"
#include "log.h"
#include <SDL2/SDL_net.h>
#include <unistd.h>
static TCPsocket _sock_host = NULL;
static TCPsocket _sock_other = NULL;
int
netcode_init_host(uint16_t port)
{
IPaddress ip;
if (SDLNet_ResolveHost(&ip, NULL, port) < 0) {
log_error("%s", SDLNet_GetError());
return -1;
}
_sock_host = SDLNet_TCP_Open(&ip);
if (_sock_host == NULL) {
log_error("%s", SDLNet_GetError());
return -1;
}
log_info("waiting for client");
for (;;) {
_sock_other = SDLNet_TCP_Accept(_sock_host);
if (_sock_other != NULL)
break;
sleep(0);
}
log_info("syncing");
char buf[3];
if (netcode_recv(buf, 3)) {
log_error("netcode_recv failed");
netcode_deinit();
return -1;
}
log_trace("received '%s'", buf);
return 0;
}
int
netcode_init_client(const char *host, uint16_t port)
{
IPaddress ip;
if (SDLNet_ResolveHost(&ip, host, port)) {
log_error("%s", SDLNet_GetError());
return -1;
}
_sock_other = SDLNet_TCP_Open(&ip);
if (_sock_other == NULL) {
log_error("%s", SDLNet_GetError());
return -1;
}
log_info("syncing");
if (netcode_send("yo", 3)) {
log_error("netcode_send failed");
netcode_deinit();
return -1;
}
return 0;
}
void
netcode_deinit(void)
{
if (_sock_other != NULL) {
SDLNet_TCP_Close(_sock_other);
_sock_other = NULL;
}
if (_sock_host != NULL) {
SDLNet_TCP_Close(_sock_host);
_sock_host = NULL;
}
}
int
netcode_host(void)
{
return (_sock_host != NULL);
}
int
netcode_send(void *data, int size)
{
if (SDLNet_TCP_Send(_sock_other, data, size) != size) {
log_error("%s", SDLNet_GetError());
return -1;
}
return 0;
}
int
netcode_recv(void *data, int size)
{
if (SDLNet_TCP_Recv(_sock_other, data, size) != size) {
log_error("%s", SDLNet_GetError());
return -1;
}
return 0;
}
int
netcode_ping(void)
{
char a = 0;
if (_sock_host != NULL)
return netcode_recv(&a, 1);
return netcode_send(&a, 1);
}
|