summaryrefslogtreecommitdiffstats
path: root/src/Socket.cpp
blob: b3de080bb149d0edfe5081bd12ed5a517241df44 (plain) (blame)
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
#include "Socket.hpp"

#include <thread>
#include <stdexcept>

Socket::Socket(std::string address, unsigned short port) {    
    if (SDLNet_Init() == -1)
        throw std::runtime_error("SDL_Net initalization failed: " + std::string(SDLNet_GetError()));

    if (SDLNet_ResolveHost(&server, address.c_str(), port) == -1)
        throw std::runtime_error("Hostname not resolved: " + std::string(SDLNet_GetError()));

    socket = SDLNet_TCP_Open(&server);
    if (!socket)
        throw std::runtime_error(std::string(SDLNet_GetError()));
}

Socket::~Socket() {
    SDLNet_TCP_Close(socket);

    SDLNet_Quit();
}

void Socket::Read(unsigned char *buffPtr, size_t buffLen) {    
    size_t totalReceived = 0;
    while (buffLen > totalReceived) {
        size_t received = SDLNet_TCP_Recv(socket, buffPtr + totalReceived, buffLen - totalReceived);
        if ( received <= 0)
            throw std::runtime_error("Data receiving failed: " + std::string(SDLNet_GetError()));
        totalReceived += received;
    }
}

void Socket::Write(unsigned char *buffPtr, size_t buffLen) {
    if (SDLNet_TCP_Send(socket, buffPtr, buffLen) < buffLen)
        throw std::runtime_error("Data sending failed: " + std::string(SDLNet_GetError()));
}