File UdpServer.hpp¶
File List > Engine > include > Network > UdpServer.hpp
Go to the documentation of this file
#ifndef ENGINE_NETWORK_UDP_SERVER_HPP_
#define ENGINE_NETWORK_UDP_SERVER_HPP_
#include "Compat/EnetWrapper.hpp"
#include "Network/ByteStream.hpp"
#include "Network/UdpPacket.hpp"
#include <atomic>
#include <functional>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
namespace Engine::Network {
class UdpServer {
public:
UdpServer();
virtual ~UdpServer();
// Non-copyable
UdpServer(const UdpServer&) = delete;
UdpServer& operator=(const UdpServer&) = delete;
bool Start(uint16_t port, size_t maxClients = 32, size_t channels = 2,
bool multiThreaded = true);
void Stop();
[[nodiscard]] bool IsRunning() const noexcept {
return isRunning_.load();
}
[[nodiscard]] uint16_t GetPort() const noexcept {
return port_;
}
[[nodiscard]] size_t GetConnectedCount() const;
void PollEvents(const std::function<void(const NetworkEvent&)>& handler);
void SendPacket(ENetPeer* peer, const uint8_t* data, size_t size, bool reliable = true,
uint8_t channel = 0);
void SendPacket(ENetPeer* peer, const ByteWriter& writer, bool reliable = true,
uint8_t channel = 0);
void BroadcastPacket(const uint8_t* data, size_t size, bool reliable = true,
uint8_t channel = 0);
void BroadcastPacket(const ByteWriter& writer, bool reliable = true, uint8_t channel = 0);
void DisconnectPeer(ENetPeer* peer, uint32_t data = 0);
protected:
void NetworkIoLoop();
void ProcessEnetEvents();
ENetHost* serverHost_{nullptr};
uint16_t port_{0};
bool multiThreaded_{true};
std::atomic<bool> isRunning_{false};
std::thread ioThread_;
mutable std::mutex queueMutex_;
std::queue<NetworkEvent> incomingEvents_;
mutable std::mutex sendMutex_;
};
} // namespace Engine::Network
#endif // ENGINE_NETWORK_UDP_SERVER_HPP_