58 lines
1.7 KiB
C
Raw Normal View History

2019-10-26 01:51:40 +02:00
#pragma once
#include <thread>
#include <event.h>
#include <memory>
#include <deque>
#include <mutex>
#include <pipes/buffer.h>
#include <functional>
#ifndef WIN32
#include <netinet/in.h>
#else
#include <WinSock2.h>
#endif
namespace tc::connection {
class UDPSocket {
public:
explicit UDPSocket(const sockaddr_storage& /* target */);
~UDPSocket();
2019-10-26 01:51:40 +02:00
const sockaddr_storage& remote_address() { return this->_remote_address; }
2019-10-26 01:51:40 +02:00
bool initialize();
void finalize();
2019-10-26 01:51:40 +02:00
void send_message(const pipes::buffer_view& /* message */);
2019-10-26 01:51:40 +02:00
/* Callbacks are called within the IO loop. Do not call any other functions except send_message! */
std::function<void(const pipes::buffer_view& /* message */)> on_data;
std::function<void(int /* error code */, int /* description */)> on_fatal_error;
2019-10-26 01:51:40 +02:00
const std::thread& io_thread() { return this->_io_thread; }
private:
2020-04-16 13:12:00 +02:00
static void _io_execute(void *_ptr_socket, void *_ptr_event_base);
static void _callback_read(evutil_socket_t, short, void*);
static void _callback_write(evutil_socket_t, short, void*);
2019-10-26 01:51:40 +02:00
2020-04-16 13:12:00 +02:00
void io_execute(void*);
void callback_read(evutil_socket_t);
void callback_write(evutil_socket_t);
2019-10-26 01:51:40 +02:00
sockaddr_storage _remote_address;
2019-10-26 01:51:40 +02:00
int file_descriptor = 0;
2019-10-26 01:51:40 +02:00
std::recursive_mutex io_lock;
std::thread _io_thread;
event_base* io_base = nullptr;
2019-10-26 01:51:40 +02:00
event* event_read = nullptr;
event* event_write = nullptr;
2019-10-26 01:51:40 +02:00
std::deque<pipes::buffer> write_queue;
};
2019-10-26 01:51:40 +02:00
}