aboutsummaryrefslogtreecommitdiffstats
path: root/include/tcpclient.h
blob: 383b913c9967bb9e6451aa7cb720c439e5d26008 (plain)
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
/* Copyright (C) 2022 The Qt Company Ltd.
 *
 * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
*/

#pragma once

#include <iostream>
#include <string>
#include <map>
#define BUFFER_SIZE 1024

#if __APPLE__ || __MACH__ || __linux__
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    #include <netdb.h>
    typedef int type_socket;
#else
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <process.h>
    // Need to link with Ws2_32.lib
    #pragma comment (lib, "Ws2_32.lib")
    typedef size_t ssize_t;
    typedef SOCKET type_socket;
#endif

enum TcpReturnValues {
    e_tcp_success           = 0,
    e_tcp_error_conn        = 1,
    e_tcp_error_send        = 2,
    e_tcp_error_recv        = 3,
    e_tcp_error_hostname    = 4,
    e_tcp_fail_socket       = 5
};

class TcpClient
{
public:
    TcpClient(const std::string &connAddr, uint16_t port);
    ~TcpClient() { doCloseSocket(); }

    int sendAndReceive(const std::string &message, std::string &reply);
    std::string errorString(int errCode) {return m_tcpReturnStr[errCode];};

private:
    type_socket m_socketFD;
    sockaddr_in m_server;
    std::map<int, std::string> m_tcpReturnStr = {
        {e_tcp_success,         "TCP: Ok"},
        {e_tcp_error_conn,      "TCP: Error when connecting"},
        {e_tcp_error_hostname,  "TCP: Error finding the hostname"},
        {e_tcp_error_recv,      "TCP: Error receiving data"},
        {e_tcp_error_send,      "TCP: Error sending data"},
        {e_tcp_fail_socket,     "TCP: Fail setting up the socket"}
    };

    void doCloseSocket()
    {
#if __APPLE__ || __MACH__  || __linux__
        close(m_socketFD);
#else
        closesocket(m_socketFD);
#endif
    }

};