Program Listing for File tcp_server.hpp

Return to documentation for file (src/tap/communication/tcp-server/tcp_server.hpp)

/*
 * Copyright (c) 2020-2021 Advanced Robotics at the University of Washington <robomstr@uw.edu>
 *
 * This file is part of Taproot.
 *
 * Taproot is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Taproot is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Taproot.  If not, see <https://www.gnu.org/licenses/>.
 */

#ifndef TAPROOT_TCP_SERVER_HPP_
#define TAPROOT_TCP_SERVER_HPP_

#ifdef PLATFORM_HOSTED

#ifdef __linux__
#include <netinet/in.h>
#endif

#include <atomic>
#include <cstdint>

namespace tap
{
namespace communication
{
class TCPServer
{
// Make constructor and destructor public if in unit tests environment.
#ifdef ENV_UNIT_TESTS
public:
#endif
    TCPServer(int portnumber);

    ~TCPServer();

public:
    /* PortNumber which the server will try to open on. This seems finicky
     * as it's possible that port is in use, but I don't know how to do
     * better (Tenzin)*/
    static const int16_t PORT_NUMBER = 8888;
    static const uint8_t LISTEN_QUEUE_SIZE = 5;  // 5 is max on most systems

    static TCPServer* MainServer();

    void getConnection();

    void closeConnection();

    uint16_t getPortNumber();

    void writeToClient(const char* message, int32_t messageLength);

private:
#ifdef __linux__
    bool socketOpened;
    bool clientConnected;
    int16_t listenFileDescriptor;  // File descriptor which server gets connection requests
    int16_t mainClientDescriptor;  // File Descriptor which we communciate with
    sockaddr_in serverAddress;
    int16_t portNumber;  // portNumber the server is bound to
#endif                   // __linux__

    // Singleton server.
    static TCPServer mainServer;
};  // TCPServer

#ifdef __linux__
void readMessage(int16_t fileDescriptor, char* readBuffer, uint16_t messageLength);

void writeMessage(int16_t fileDescriptor, const char* message, uint16_t bytes);

int32_t readInt32(int16_t fileDescriptor);
#endif  // __linux__

}  // namespace communication

}  // namespace tap

#endif  // PLATFORM_HOSTED

#endif  // TAPROOT_TCP_SERVER_HPP_