src.dualinventive.com/dinet/sec-multi-proxy/include/server/UdpServer.h

83 lines
2.2 KiB
C++

/*
* UdpServer.h
*/
#ifndef INCLUDE_SERVER_UDPSERVER_H_
#define INCLUDE_SERVER_UDPSERVER_H_
#include <memory>
#include <thread>
#include <atomic>
#include <unordered_map>
#include <device/DeviceFacade.h>
#include <server/ProtocolFacade.h>
#include <server/UDPConnection.h>
#include <di/Buffer.h>
#include <Message.h>
#include <di/Timer.h>
using namespace std;
/**
* UdpServer is the UDP server it listens for UDP diagrams.
*/
class UdpServer {
public:
const int kTimeoutMs = 500;
const size_t kReadSize = UINT16_MAX;
const int kConnectionTimeoutMs = 90000;
/**
* constructor for udp server
* @param port port number
* @param connectionTimeoutMs the timeout of when to remove a UDP connection
* @param d pointer to device facade
* @throw int socket creation failed, socket payload malloc failed, socket bind failed
*/
UdpServer(uint16_t port, uint64_t connectionTimeoutMs, const std::shared_ptr<DeviceFacade> &d);
/**
* deconstucor for udp server
*/
~UdpServer();
/**
* sets socket to be blocking
* @param blockingToggle true is block false is dont block
*/
bool setBlocking(const bool blockingToggle);
/**
* bind the socket
* @throw int socket bind failed
*/
void bind(void);
/**
* spawn a new thread which listens to udp packets
*/
void listen(void);
void write(const shared_ptr<struct sockaddr_in> &address, const std::shared_ptr<Di::Buffer> &buf);
private:
uint16_t __port; /**< Listening port number */
uint64_t __connectionTimeoutMs;
mutable std::shared_timed_mutex __mutUDPConnections;
std::unordered_map<std::string, std::shared_ptr<UDPConnection>> __udpConnections;
uint8_t *__udpPayload; /**< buffer which is used to read UDP diagrams of size kReadSize */
std::shared_ptr<ProtocolFacade> __protoFacade;
std::shared_ptr<DeviceFacade> __deviceFacade;
std::shared_ptr<std::thread> __listenThread; /**< thread for listening to udp datagrams */
int __fd; /**< Socket file descriptor */
std::atomic_bool __running; /**< boolean to see if the program is running */
Di::Timer __connectionTimeoutTimer;
void __listen(void);
void __read(const shared_ptr<struct sockaddr_in> &address, const std::shared_ptr<Di::Buffer> &buf);
void __checkConnectionTimeout(Di::Timer* t);
};
#endif // INCLUDE_SERVER_UDPSERVER_H_