aboutsummaryrefslogtreecommitdiffstats
path: root/include/tcpserver.h
blob: a031b88ea4e455c7a98eab7edb0b5a7135da9158 (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
/* 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 <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>

#define MAX_CLIENTS 30
#define TRUE 1
#define FALSE 0

#define CLIENT_CLOSED_MSG  "closed"

#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>
    #include <sys/time.h>
typedef int type_socket;
#else
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <winsock2.h>
    #include <ws2tcpip.h>
    // Need to link with Ws2_32.lib
    #pragma comment (lib, "Ws2_32.lib")
    typedef SOCKET type_socket;
#endif

#define BUFFER_SIZE 1024

class TcpServer
{
public:
    explicit TcpServer(uint16_t serverPort);
    ~TcpServer();

    std::string listenToClients(int &socket);
    int sendResponse(int socketIndex, const std::string &message);

private:
    type_socket m_masterSocket;
    type_socket m_clientSocket[MAX_CLIENTS];
    int m_addrlen;
    char m_buffer[BUFFER_SIZE]; // data buffer
    fd_set m_readfds; // set of socket descriptors
    struct sockaddr_in m_address;

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

};