2020-06-13 19:46:12 +00:00
|
|
|
#include "TCPSend.h"
|
|
|
|
|
2020-06-16 11:55:38 +00:00
|
|
|
#if defined(_DEBUG)
|
|
|
|
#include <stdio.h>
|
|
|
|
#define DPRINTF printf
|
|
|
|
#else
|
|
|
|
#define DPRINTF(a, ...)
|
|
|
|
#endif
|
|
|
|
|
2020-06-13 19:46:12 +00:00
|
|
|
static const int RETRY_COUNT = 10; // shrugs
|
|
|
|
|
|
|
|
TCPSend::TCPSend(std::string& ip, int port) :
|
|
|
|
m_ip(ip),
|
|
|
|
m_port(port),
|
|
|
|
m_socket(nullptr)
|
|
|
|
{
|
|
|
|
SDLNet_Init();
|
|
|
|
}
|
|
|
|
|
|
|
|
TCPSend::~TCPSend()
|
|
|
|
{
|
|
|
|
if (m_socket) {
|
|
|
|
SDLNet_TCP_Close(m_socket);
|
|
|
|
m_socket = nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
SDLNet_Quit(); // unload lib (winsock dll for windows)
|
|
|
|
}
|
|
|
|
|
|
|
|
bool TCPSend::Send(const void * data, int length)
|
|
|
|
{
|
|
|
|
// If we failed bail out
|
|
|
|
if (!Connected()) {
|
2020-06-16 11:55:38 +00:00
|
|
|
DPRINTF("Not connected\n");
|
2020-06-13 19:46:12 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2020-06-16 11:55:38 +00:00
|
|
|
DPRINTF("Sending %i bytes\n", length);
|
|
|
|
|
2020-06-13 19:46:12 +00:00
|
|
|
if (!length) {
|
|
|
|
return true; // 0 sized packet will blow our connex
|
|
|
|
}
|
|
|
|
|
|
|
|
int sent = 0;
|
|
|
|
|
|
|
|
sent = SDLNet_TCP_Send(m_socket, &length, sizeof(int)); // pack the length at the start of transmission.
|
|
|
|
sent = SDLNet_TCP_Send(m_socket, data, length);
|
|
|
|
|
|
|
|
if (sent < length) {
|
|
|
|
SDLNet_TCP_Close(m_socket);
|
|
|
|
m_socket = nullptr;
|
|
|
|
}
|
|
|
|
|
2020-06-16 11:55:38 +00:00
|
|
|
return true;
|
2020-06-13 19:46:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
bool TCPSend::Connected()
|
|
|
|
{
|
|
|
|
return m_socket != 0;
|
|
|
|
}
|
|
|
|
|
2020-06-16 11:55:38 +00:00
|
|
|
bool TCPSend::Connect()
|
2020-06-13 19:46:12 +00:00
|
|
|
{
|
|
|
|
IPaddress ip;
|
|
|
|
int result = SDLNet_ResolveHost(&ip, m_ip.c_str(), m_port);
|
|
|
|
|
|
|
|
if (result == 0) {
|
|
|
|
m_socket = SDLNet_TCP_Open(&ip);
|
|
|
|
}
|
|
|
|
|
2020-06-16 11:55:38 +00:00
|
|
|
return Connected();
|
2020-06-13 19:46:12 +00:00
|
|
|
}
|