diff options
Diffstat (limited to 'src/netcode.c')
-rw-r--r-- | src/netcode.c | 101 |
1 files changed, 101 insertions, 0 deletions
diff --git a/src/netcode.c b/src/netcode.c new file mode 100644 index 0000000..b3ac6c3 --- /dev/null +++ b/src/netcode.c @@ -0,0 +1,101 @@ +#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_send(void *data, size_t size) +{ + if (SDLNet_TCP_Send(_sock_other, data, size) < 0) { + log_error("%s", SDLNet_GetError()); + return -1; + } + return 0; +} + +int +netcode_recv(void *data, size_t size) +{ + if (SDLNet_TCP_Recv(_sock_other, data, size) < 0) { + log_error("%s", SDLNet_GetError()); + return -1; + } + return 0; +} |