handmade/include/UDPbase.h
Bubblegumdrop 9e957d466f Client and Server tweaks. This commit breaks the Client.
Server listens correctly with threads and stdin reader thread.

Client does nothing currently gutting UDP_Write for a UDPbase class
introduced in this commit.
2022-01-08 18:59:40 -05:00

62 lines
1.3 KiB
C++

#pragma once
#include <string>
#include <SDL_net.h>
#define MAX_PACKET_SIZE 250
class UDPbase
{
IPaddress addr;
public:
UDPbase (const char* host, const Uint16 port)
{
if (SDLNet_ResolveHost (&addr, host, SDLNet_Read16 (&port)) < 0)
{
throw "SDLNet_ResolveHost: " + std::string (SDLNet_GetError ());
}
}
~UDPbase (void)
{
}
UDPsocket Open (void)
{
return Open (addr.port);
}
UDPsocket Open (const Uint16 port)
{
UDPsocket sock = NULL;
IPaddress* addr;
if (NULL == (sock = SDLNet_UDP_Open (port)))
{
throw "SDLNet_UDP_Open: " + std::string (SDLNet_GetError ());
}
if (NULL != (addr = SDLNet_UDP_GetPeerAddress (sock, -1)))
{
SDL_Log ("Opened UDP port %d", SDLNet_Read16 (&addr->port));
}
return sock;
}
int Bind (UDPsocket sock, const int channel)
{
int binding;
SDL_assert (NULL != sock);
if (-1 == (binding = SDLNet_UDP_Bind (sock, channel, &addr)))
{
throw "SDLNet_UDP_Bind: " + std::string (SDLNet_GetError ());
}
SDL_Log ("Binding UDP socket %s ch%d", this->toString ().c_str (), binding);
return binding;
}
void Close (UDPsocket sock)
{
SDL_assert (NULL != sock);
SDLNet_UDP_Close (sock);
sock = NULL;
}
std::string toString (void)
{
return std::string (SDLNet_ResolveIP (&addr)) + ":" + std::to_string (addr.port);
}
};