r-type  0.0.0
R-Type main
Loading...
Searching...
No Matches
srv::AsioServer Class Referencefinal

High-performance UDP server implementation using ASIO library. More...

#include <AsioServer.hpp>

+ Inheritance diagram for srv::AsioServer:
+ Collaboration diagram for srv::AsioServer:

Public Member Functions

 AsioServer ()
 Constructor.
 
 ~AsioServer () override
 Destructor.
 
const std::string getName () const override
 
utl::PluginType getType () const override
 
void init (const std::string &host, std::uint16_t port) override
 
void start () override
 
void stop () override
 
void update () override
 
void sendToClient (std::uint32_t sessionId, const std::vector< std::uint8_t > &data, bool reliable=false) override
 
void sendToAllClients (const std::vector< std::uint8_t > &data, bool reliable=false) override
 
void disconnectClient (std::uint32_t sessionId) override
 
std::size_t getClientCount () const override
 
std::vector< std::uint32_t > getConnectedSessions () const override
 
bool isRunning () const override
 
void setTickRate (std::uint16_t tickRate) override
 
void setServerCapabilities (std::uint32_t caps) override
 
- Public Member Functions inherited from srv::INetworkServer
virtual ~INetworkServer ()=default
 
virtual void init (const std::string &host, uint16_t port)=0
 
- Public Member Functions inherited from utl::IPlugin
virtual ~IPlugin ()=default
 

Private Member Functions

void setupPacketHandlers ()
 Initialize packet handlers.
 
void startReceive ()
 Start receiving packets asynchronously.
 
void handleReceive (std::size_t bytesReceived)
 Handle received packet.
 
void networkThreadLoop () const
 Network thread main loop.
 
std::uint32_t generateSessionId () const
 Generate unique session ID.
 
std::string endpointToString (const asio::ip::udp::endpoint &endpoint)
 Get endpoint string representation.
 
void sendPacketImmediate (const std::vector< std::uint8_t > &data, const asio::ip::udp::endpoint &destination)
 Send packet immediately.
 
rnp::HandlerResult handleConnect (const rnp::PacketConnect &packet, const rnp::PacketContext &context)
 Handle CONNECT packet.
 
rnp::HandlerResult handleDisconnect (const rnp::PacketDisconnect &packet, const rnp::PacketContext &context)
 Handle DISCONNECT packet.
 
rnp::HandlerResult handlePing (const rnp::PacketPingPong &packet, const rnp::PacketContext &context)
 Handle PING packet.
 
rnp::HandlerResult handlePong (const rnp::PacketPingPong &packet, const rnp::PacketContext &context)
 Handle PONG packet.
 
void sendPong (std::uint32_t nonce, const asio::ip::udp::endpoint &destination, std::uint32_t sessionId)
 Send PONG response.
 
void sendConnectAccept (std::uint32_t sessionId, const asio::ip::udp::endpoint &destination)
 Send CONNECT_ACCEPT response.
 
void sendError (rnp::ErrorCode errorCode, const std::string &description, const asio::ip::udp::endpoint &destination, std::uint32_t sessionId)
 Send ERROR packet.
 
void updateClientManagement ()
 Update client timeouts and send pings.
 
void processSendQueue ()
 Process send queue.
 
void processEventBusEvents ()
 Process EventBus events for network operations.
 
void handleSendToClientEvent (const utl::Event &event)
 Handle send to client event from EventBus.
 
void handleBroadcastEvent (const utl::Event &event)
 Handle broadcast event from EventBus.
 
void handleSendEntityEventToClients (const utl::Event &event)
 Handle send entity event to clients from EventBus.
 
rnp::HandlerResult handleEntityEvent (const std::vector< rnp::EventRecord > &events, const rnp::PacketContext &context) const
 Handle entity event packet (including player inputs)
 
rnp::HandlerResult handleLobbyListRequest (const rnp::PacketContext &context)
 Handle LOBBY_LIST_REQUEST packet.
 
rnp::HandlerResult handleLobbyCreate (const rnp::PacketLobbyCreate &packet, const rnp::PacketContext &context)
 Handle LOBBY_CREATE packet.
 
rnp::HandlerResult handleLobbyJoin (const rnp::PacketLobbyJoin &packet, const rnp::PacketContext &context)
 Handle LOBBY_JOIN packet.
 
rnp::HandlerResult handleLobbyLeave (const rnp::PacketContext &context)
 Handle LOBBY_LEAVE packet.
 
void sendLobbyList (std::uint32_t sessionId)
 Send lobby list to client.
 
std::uint32_t createLobby (const std::string &lobbyName, std::uint32_t hostSessionId, std::uint8_t maxPlayers, std::uint8_t gameMode)
 Create new lobby.
 
LobbyStatus joinLobby (std::uint32_t lobbyId, std::uint32_t sessionId)
 Join player to lobby.
 
void leaveLobby (std::uint32_t sessionId)
 Remove player from lobby.
 
void broadcastLobbyUpdate (std::uint32_t lobbyId)
 Broadcast lobby update to all lobby members.
 
rnp::HandlerResult handleStartGameRequest (const rnp::PacketStartGameRequest &packet, const rnp::PacketContext &context)
 Handle START_GAME_REQUEST packet.
 
void broadcastGameOverToLobby (std::uint32_t lobbyId)
 Broadcast game start to all players in lobby.
 
void broadcastGameStart (std::uint32_t lobbyId)
 Broadcast game start notification to all lobby members.
 
rnp::LobbyInfo lobbyToLobbyInfo (const Lobby &lobby)
 Convert Lobby to LobbyInfo for network transmission.
 
void sendLobbyCreateResponse (std::uint32_t sessionId, std::uint32_t lobbyId, bool success, rnp::ErrorCode errorCode=rnp::ErrorCode::INTERNAL_ERROR)
 Send lobby create response.
 
void sendLobbyJoinResponse (std::uint32_t sessionId, std::uint32_t lobbyId, bool success, rnp::ErrorCode errorCode, const rnp::LobbyInfo *lobbyInfo=nullptr)
 Send lobby join response.
 
void handleGameOverEvent (const utl::Event &event)
 Handle GAME_OVER event from game server.
 
void broadcastGameOverToLobby (std::uint32_t lobbyId, const std::vector< std::uint8_t > &gameOverData)
 Broadcast GAME_OVER packet to all players in a lobby.
 
void cleanupEmptyLobbies ()
 Clean up empty lobbies.
 

Private Attributes

std::unique_ptr< asio::io_context > m_ioContext
 ASIO I/O context for async operations.
 
std::unique_ptr< asio::ip::udp::socket > m_socket
 UDP socket for network communication.
 
std::unique_ptr< std::thread > m_networkThread
 Dedicated network thread.
 
std::string m_host
 Server bind address (e.g., "0.0.0.0")
 
std::uint16_t m_port
 Server listening port (default: 4567)
 
std::uint16_t m_tickRate
 Server tick rate in Hz.
 
std::uint32_t m_serverCaps
 Server capability flags.
 
std::atomic< bool > m_running
 Server running state (atomic for thread safety)
 
std::atomic< bool > m_started
 Server started state.
 
std::unordered_map< std::uint32_t, ClientSessionm_clients
 Map of session ID to client session.
 
std::unordered_map< std::string, std::uint32_t > m_endpointToSession
 Map of endpoint string to session ID.
 
std::uint32_t m_nextSessionId
 Next available session ID.
 
std::mutex m_clientsMutex
 Mutex for thread-safe client access.
 
std::unordered_map< std::uint32_t, Lobbym_lobbies
 Map of lobby ID to lobby data.
 
std::uint32_t m_nextLobbyId
 Next available lobby ID.
 
std::mutex m_lobbiesMutex
 Mutex for thread-safe lobby access.
 
std::unique_ptr< rnp::HandlerPacketm_packetHandler
 RNP packet handler instance.
 
std::queue< QueuedPacketm_sendQueue
 Queue of packets waiting to be sent.
 
std::mutex m_sendQueueMutex
 Mutex for send queue access.
 
std::mutex m_socketMutex
 Mutex for socket operations.
 
std::array< std::uint8_t, MAX_LEN_RECV_BUFFERm_recvBuffer
 Buffer for receiving UDP packets.
 
asio::ip::udp::endpoint m_senderEndpoint
 Endpoint of last packet sender.
 
std::chrono::steady_clock::time_point m_lastPingTime
 Timestamp of last ping sweep.
 
std::chrono::milliseconds m_pingInterval
 Interval between ping sweeps (5000ms)
 
std::chrono::milliseconds m_clientTimeout
 Client timeout duration (15000ms)
 
std::uint32_t m_componentId
 Component ID for event bus registration.
 
utl::EventBusm_eventBus
 

Detailed Description

High-performance UDP server implementation using ASIO library.

This class provides a complete multiplayer game server implementation with:

  • Asynchronous UDP networking
  • Client session management
  • Lobby system for matchmaking
  • Packet routing and handling
  • Event bus integration
  • Thread-safe operations

The server runs its network operations on a separate thread and communicates with the game engine via an event bus system.

Definition at line 157 of file AsioServer.hpp.

Constructor & Destructor Documentation

◆ AsioServer()

srv::AsioServer::AsioServer ( )

◆ ~AsioServer()

srv::AsioServer::~AsioServer ( )
override

Destructor.

Definition at line 44 of file asioServer.cpp.

References stop().

+ Here is the call graph for this function:

Member Function Documentation

◆ broadcastGameOverToLobby() [1/2]

void srv::AsioServer::broadcastGameOverToLobby ( std::uint32_t lobbyId)
private

Broadcast game start to all players in lobby.

Parameters
lobbyIdTarget lobby ID

Broadcast game start notification to all lobby members

Parameters
lobbyIdLobby ID that is starting

Broadcast game over notification to lobby members

Parameters
lobbyIdLobby ID that finished

Referenced by handleGameOverEvent().

+ Here is the caller graph for this function:

◆ broadcastGameOverToLobby() [2/2]

void srv::AsioServer::broadcastGameOverToLobby ( std::uint32_t lobbyId,
const std::vector< std::uint8_t > & gameOverData )
private

Broadcast GAME_OVER packet to all players in a lobby.

Parameters
lobbyIdTarget lobby ID
gameOverDataGame over packet data

Definition at line 1370 of file asioServer.cpp.

References rnp::GAME_OVER, rnp::Serializer::getData(), utl::INFO, rnp::PacketHeader::length, utl::Logger::log(), m_clients, m_clientsMutex, m_lobbies, m_lobbiesMutex, sendPacketImmediate(), rnp::Serializer::serializeHeader(), rnp::PacketHeader::sessionId, and rnp::PacketHeader::type.

+ Here is the call graph for this function:

◆ broadcastGameStart()

void srv::AsioServer::broadcastGameStart ( std::uint32_t lobbyId)
private

◆ broadcastLobbyUpdate()

void srv::AsioServer::broadcastLobbyUpdate ( std::uint32_t lobbyId)
private

Broadcast lobby update to all lobby members.

Parameters
lobbyIdTarget lobby ID

Broadcast lobby update to all lobby members

Parameters
lobbyIdLobby ID to broadcast update for

Definition at line 1409 of file asioServer.cpp.

References rnp::Serializer::getData(), utl::INFO, rnp::PacketHeader::length, rnp::LOBBY_UPDATE, rnp::PacketLobbyUpdate::lobbyInfo, lobbyToLobbyInfo(), utl::Logger::log(), m_clients, m_clientsMutex, m_lobbies, m_lobbiesMutex, sendPacketImmediate(), rnp::Serializer::serializeHeader(), rnp::Serializer::serializeLobbyUpdate(), rnp::PacketHeader::sessionId, rnp::PacketHeader::type, and update().

Referenced by disconnectClient(), handleLobbyCreate(), handleLobbyJoin(), and handleLobbyLeave().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ cleanupEmptyLobbies()

void srv::AsioServer::cleanupEmptyLobbies ( )
private

Clean up empty lobbies.

Remove empty lobbies from server

Called periodically to clean up abandoned lobbies

Definition at line 1540 of file asioServer.cpp.

References utl::INFO, utl::Logger::log(), and m_lobbies.

Referenced by leaveLobby().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createLobby()

std::uint32_t srv::AsioServer::createLobby ( const std::string & lobbyName,
std::uint32_t hostSessionId,
std::uint8_t maxPlayers,
std::uint8_t gameMode )
private

Create new lobby.

Parameters
nameLobby name
hostSessionHost session ID
maxPlayersMaximum players
gameModeGame mode
Returns
New lobby ID

Create a new lobby

Parameters
lobbyNameDisplay name for the lobby
hostSessionIdSession ID of the lobby host
maxPlayersMaximum number of players (1-8)
gameModeGame mode identifier
Returns
New lobby ID

Definition at line 1213 of file asioServer.cpp.

References utl::INFO, utl::Logger::log(), m_lobbies, m_lobbiesMutex, m_nextLobbyId, and srv::Lobby::playerSessions.

Referenced by handleLobbyCreate().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ disconnectClient()

◆ endpointToString()

std::string srv::AsioServer::endpointToString ( const asio::ip::udp::endpoint & endpoint)
private

Get endpoint string representation.

Parameters
endpointUDP endpoint
Returns
String representation

Convert endpoint to string representation

Parameters
endpointUDP endpoint
Returns
String in format "IP:PORT"

Definition at line 526 of file asioServer.cpp.

Referenced by disconnectClient(), handleConnect(), and handleDisconnect().

+ Here is the caller graph for this function:

◆ generateSessionId()

std::uint32_t srv::AsioServer::generateSessionId ( ) const
private

Generate unique session ID.

Returns
New session ID

Generate a unique session ID

Returns
New session ID (cryptographically random)

Definition at line 511 of file asioServer.cpp.

References m_clients.

Referenced by handleConnect().

+ Here is the caller graph for this function:

◆ getClientCount()

std::size_t srv::AsioServer::getClientCount ( ) const
nodiscardoverridevirtual

Implements srv::INetworkServer.

Definition at line 308 of file asioServer.cpp.

References m_clients, and m_clientsMutex.

◆ getConnectedSessions()

std::vector< std::uint32_t > srv::AsioServer::getConnectedSessions ( ) const
nodiscardoverridevirtual

Implements srv::INetworkServer.

Definition at line 314 of file asioServer.cpp.

References m_clients, and m_clientsMutex.

◆ getName()

const std::string srv::AsioServer::getName ( ) const
inlinenodiscardoverridevirtual

Implements utl::IPlugin.

Definition at line 171 of file AsioServer.hpp.

◆ getType()

utl::PluginType srv::AsioServer::getType ( ) const
inlinenodiscardoverridevirtual

Implements utl::IPlugin.

Definition at line 172 of file AsioServer.hpp.

References utl::NETWORK_CLIENT.

◆ handleBroadcastEvent()

void srv::AsioServer::handleBroadcastEvent ( const utl::Event & event)
private

Handle broadcast event from EventBus.

Parameters
eventBroadcast event

Handle broadcast event from event bus

Parameters
eventEvent containing packet data to broadcast

Definition at line 903 of file asioServer.cpp.

References utl::Event::data, and sendToAllClients().

Referenced by processEventBusEvents().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleConnect()

◆ handleDisconnect()

rnp::HandlerResult srv::AsioServer::handleDisconnect ( const rnp::PacketDisconnect & packet,
const rnp::PacketContext & context )
private

Handle DISCONNECT packet.

Parameters
packetDisconnect packet
contextPacket context
Returns
Handler result

Definition at line 637 of file asioServer.cpp.

References endpointToString(), utl::GAME_LOGIC, m_clients, m_clientsMutex, m_componentId, m_endpointToSession, m_eventBus, utl::PLAYER_DISCONNECTED, utl::EventBus::publish(), rnp::PacketContext::sessionId, and rnp::SUCCESS.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleEntityEvent()

rnp::HandlerResult srv::AsioServer::handleEntityEvent ( const std::vector< rnp::EventRecord > & events,
const rnp::PacketContext & context ) const
private

Handle entity event packet (including player inputs)

Parameters
eventsEntity event records
contextPacket context
Returns
Handler result

Definition at line 923 of file asioServer.cpp.

References utl::ENTITY_EVENT_RECEIVED, utl::GAME_LOGIC, utl::INFO, rnp::INPUT, utl::Logger::log(), m_componentId, m_eventBus, utl::PLAYER_INPUT_RECEIVED, utl::EventBus::publish(), rnp::PacketContext::sessionId, and rnp::SUCCESS.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleGameOverEvent()

void srv::AsioServer::handleGameOverEvent ( const utl::Event & event)
private

Handle GAME_OVER event from game server.

Parameters
eventGame over event

Handle game over event from game engine

Parameters
eventEvent containing game over data

Definition at line 1329 of file asioServer.cpp.

References broadcastGameOverToLobby(), utl::Event::data, utl::INFO, utl::Logger::log(), m_clients, m_clientsMutex, m_lobbies, and m_lobbiesMutex.

Referenced by processEventBusEvents().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleLobbyCreate()

rnp::HandlerResult srv::AsioServer::handleLobbyCreate ( const rnp::PacketLobbyCreate & packet,
const rnp::PacketContext & context )
private

Handle LOBBY_CREATE packet.

Parameters
packetLobby create packet
contextPacket context
Returns
Handler result

Definition at line 984 of file asioServer.cpp.

References rnp::ALREADY_IN_LOBBY, broadcastLobbyUpdate(), createLobby(), rnp::PacketLobbyCreate::gameMode, utl::INFO, rnp::INTERNAL_ERROR, rnp::PacketLobbyCreate::lobbyName, utl::Logger::log(), m_clients, m_clientsMutex, m_nextLobbyId, rnp::PacketLobbyCreate::maxPlayers, rnp::PacketLobbyCreate::nameLen, rnp::PROCESSING_ERROR, sendLobbyCreateResponse(), rnp::PacketContext::sessionId, rnp::SUCCESS, and rnp::UNAUTHORIZED_SESSION.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleLobbyJoin()

rnp::HandlerResult srv::AsioServer::handleLobbyJoin ( const rnp::PacketLobbyJoin & packet,
const rnp::PacketContext & context )
private

Handle LOBBY_JOIN packet.

Parameters
packetLobby join packet
contextPacket context
Returns
Handler result

Definition at line 1047 of file asioServer.cpp.

References rnp::ALREADY_IN_LOBBY, broadcastLobbyUpdate(), rnp::LobbyInfo::currentPlayers, utl::INFO, joinLobby(), rnp::LOBBY_NOT_FOUND, rnp::PacketLobbyJoin::lobbyId, lobbyToLobbyInfo(), utl::Logger::log(), m_clients, m_clientsMutex, m_lobbies, m_lobbiesMutex, rnp::LobbyInfo::maxPlayers, rnp::NONE, rnp::PROCESSING_ERROR, sendLobbyJoinResponse(), rnp::PacketContext::sessionId, rnp::SUCCESS, srv::SUCCESS, rnp::UNAUTHORIZED_SESSION, and utl::WARNING.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleLobbyLeave()

rnp::HandlerResult srv::AsioServer::handleLobbyLeave ( const rnp::PacketContext & context)
private

Handle LOBBY_LEAVE packet.

Parameters
contextPacket context
Returns
Handler result

Definition at line 1133 of file asioServer.cpp.

References broadcastLobbyUpdate(), utl::INFO, leaveLobby(), utl::Logger::log(), m_clients, m_clientsMutex, m_senderEndpoint, rnp::NOT_IN_LOBBY, rnp::PROCESSING_ERROR, sendError(), rnp::PacketContext::sessionId, rnp::SUCCESS, and rnp::UNAUTHORIZED_SESSION.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleLobbyListRequest()

rnp::HandlerResult srv::AsioServer::handleLobbyListRequest ( const rnp::PacketContext & context)
private

Handle LOBBY_LIST_REQUEST packet.

Parameters
contextPacket context
Returns
Handler result

Definition at line 964 of file asioServer.cpp.

References utl::INFO, utl::Logger::log(), m_clients, m_clientsMutex, m_senderEndpoint, rnp::PROCESSING_ERROR, sendError(), sendLobbyList(), rnp::PacketContext::sessionId, rnp::SUCCESS, and rnp::UNAUTHORIZED_SESSION.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handlePing()

rnp::HandlerResult srv::AsioServer::handlePing ( const rnp::PacketPingPong & packet,
const rnp::PacketContext & context )
private

Handle PING packet.

Parameters
packetPing packet
contextPacket context
Returns
Handler result

Definition at line 680 of file asioServer.cpp.

References m_clients, m_clientsMutex, m_senderEndpoint, rnp::PacketPingPong::nonce, rnp::PacketContext::receiveTime, sendPong(), rnp::PacketContext::sessionId, and rnp::SUCCESS.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handlePong()

rnp::HandlerResult srv::AsioServer::handlePong ( const rnp::PacketPingPong & packet,
const rnp::PacketContext & context )
private

Handle PONG packet.

Parameters
packetPong packet
contextPacket context
Returns
Handler result

Definition at line 697 of file asioServer.cpp.

References m_clients, m_clientsMutex, rnp::PacketContext::receiveTime, rnp::PacketPingPong::sendTimeMs, rnp::PacketContext::sessionId, and rnp::SUCCESS.

Referenced by setupPacketHandlers().

+ Here is the caller graph for this function:

◆ handleReceive()

void srv::AsioServer::handleReceive ( std::size_t bytesReceived)
private

◆ handleSendEntityEventToClients()

void srv::AsioServer::handleSendEntityEventToClients ( const utl::Event & event)
private

Handle send entity event to clients from EventBus.

Parameters
eventEntity event to send to clients

Handle entity event broadcast to clients

Parameters
eventEvent containing entity event data

Definition at line 913 of file asioServer.cpp.

References utl::Event::data, and sendToAllClients().

Referenced by processEventBusEvents().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleSendToClientEvent()

void srv::AsioServer::handleSendToClientEvent ( const utl::Event & event)
private

Handle send to client event from EventBus.

Parameters
eventSend to client event

Handle "send to client" event from event bus

Parameters
eventEvent containing target session and packet data

Definition at line 884 of file asioServer.cpp.

References utl::Event::data, and sendToClient().

Referenced by processEventBusEvents().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ handleStartGameRequest()

rnp::HandlerResult srv::AsioServer::handleStartGameRequest ( const rnp::PacketStartGameRequest & packet,
const rnp::PacketContext & context )
private

Handle START_GAME_REQUEST packet.

Parameters
packetStart game request packet
contextPacket context
Returns
Handler result

Definition at line 1559 of file asioServer.cpp.

References broadcastGameStart(), utl::Event::data, utl::GAME_LOGIC, rnp::IN_GAME, utl::INFO, rnp::LOBBY_NOT_FOUND, rnp::PacketStartGameRequest::lobbyId, utl::Logger::log(), m_clients, m_clientsMutex, m_componentId, m_eventBus, m_lobbies, m_lobbiesMutex, m_senderEndpoint, rnp::NOT_IN_LOBBY, rnp::PROCESSING_ERROR, utl::EventBus::publish(), sendError(), utl::SERVER_START, rnp::PacketContext::sessionId, rnp::SUCCESS, and rnp::UNAUTHORIZED_SESSION.

Referenced by setupPacketHandlers().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ init()

void srv::AsioServer::init ( const std::string & host,
std::uint16_t port )
override

Definition at line 51 of file asioServer.cpp.

References m_host, and m_port.

◆ isRunning()

bool srv::AsioServer::isRunning ( ) const
nodiscardoverridevirtual

Implements srv::INetworkServer.

Definition at line 328 of file asioServer.cpp.

References m_running.

◆ joinLobby()

LobbyStatus srv::AsioServer::joinLobby ( std::uint32_t lobbyId,
std::uint32_t sessionId )
private

Join player to lobby.

Parameters
lobbyIdTarget lobby ID
sessionIdPlayer session ID
Returns
Success status

Join an existing lobby

Parameters
lobbyIdTarget lobby ID
sessionIdJoining client's session ID
Returns
Status code indicating success or failure reason

Definition at line 1231 of file asioServer.cpp.

References srv::ALREADY_IN_LOBBY, srv::FULL, srv::IN_GAME, utl::INFO, utl::Logger::log(), m_lobbies, m_lobbiesMutex, srv::Lobby::maxPlayers, srv::NOT_FOUND, srv::Lobby::playerSessions, srv::Lobby::status, srv::SUCCESS, rnp::WAITING, and utl::WARNING.

Referenced by handleLobbyJoin().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ leaveLobby()

void srv::AsioServer::leaveLobby ( std::uint32_t sessionId)
private

Remove player from lobby.

Parameters
sessionIdPlayer session ID

Remove a client from their current lobby

Parameters
sessionIdClient's session ID

Definition at line 1277 of file asioServer.cpp.

References cleanupEmptyLobbies(), utl::INFO, utl::Logger::log(), m_clients, m_clientsMutex, m_lobbies, and m_lobbiesMutex.

Referenced by disconnectClient(), and handleLobbyLeave().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ lobbyToLobbyInfo()

rnp::LobbyInfo srv::AsioServer::lobbyToLobbyInfo ( const Lobby & lobby)
private

Convert Lobby to LobbyInfo for network transmission.

Parameters
lobbyLobby structure
Returns
LobbyInfo structure

Convert internal Lobby struct to RNP LobbyInfo

Parameters
lobbyInternal lobby structure
Returns
RNP protocol lobby info structure

Definition at line 1455 of file asioServer.cpp.

References rnp::LobbyInfo::currentPlayers, rnp::LobbyInfo::gameMode, srv::Lobby::gameMode, rnp::LobbyInfo::hostSessionId, srv::Lobby::hostSessionId, rnp::LobbyInfo::lobbyId, srv::Lobby::lobbyId, rnp::LobbyInfo::lobbyName, srv::Lobby::lobbyName, m_clients, m_clientsMutex, rnp::LobbyInfo::maxPlayers, srv::Lobby::maxPlayers, rnp::LobbyInfo::playerNames, srv::Lobby::playerSessions, rnp::LobbyInfo::status, and srv::Lobby::status.

Referenced by broadcastLobbyUpdate(), handleLobbyJoin(), and sendLobbyList().

+ Here is the caller graph for this function:

◆ networkThreadLoop()

void srv::AsioServer::networkThreadLoop ( ) const
private

Network thread main loop.

Main network thread loop

Runs the ASIO io_context and handles network events

Definition at line 476 of file asioServer.cpp.

References m_ioContext, and m_running.

Referenced by start().

+ Here is the caller graph for this function:

◆ processEventBusEvents()

void srv::AsioServer::processEventBusEvents ( )
private

Process EventBus events for network operations.

Process events from the event bus

Handles events from game engine (sends, broadcasts, etc.)

Definition at line 851 of file asioServer.cpp.

References utl::BROADCAST_WORLD_STATE, utl::EventBus::consumeForTarget(), utl::GAME_OVER, handleBroadcastEvent(), handleGameOverEvent(), handleSendEntityEventToClients(), handleSendToClientEvent(), m_componentId, m_eventBus, utl::SEND_ENTITY_EVENTS, and utl::SEND_TO_CLIENT.

Referenced by update().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ processSendQueue()

void srv::AsioServer::processSendQueue ( )
private

Process send queue.

Process outgoing packet queue

Sends all queued packets via UDP socket

Definition at line 840 of file asioServer.cpp.

References srv::QueuedPacket::data, srv::QueuedPacket::destination, m_sendQueue, m_sendQueueMutex, and sendPacketImmediate().

Referenced by update().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendConnectAccept()

void srv::AsioServer::sendConnectAccept ( std::uint32_t sessionId,
const asio::ip::udp::endpoint & destination )
private

Send CONNECT_ACCEPT response.

Parameters
sessionIdNew session ID
destinationTarget endpoint

Definition at line 737 of file asioServer.cpp.

References rnp::CONNECT_ACCEPT, rnp::Serializer::getData(), m_serverCaps, m_tickRate, rnp::MAX_PAYLOAD, sendPacketImmediate(), rnp::Serializer::serializeConnectAccept(), rnp::Serializer::serializeHeader(), rnp::PacketConnectAccept::sessionId, and rnp::PacketHeader::type.

Referenced by handleConnect().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendError()

void srv::AsioServer::sendError ( rnp::ErrorCode errorCode,
const std::string & description,
const asio::ip::udp::endpoint & destination,
std::uint32_t sessionId )
private

Send ERROR packet.

Parameters
errorCodeError code
descriptionError description
destinationTarget endpoint
sessionIdSession ID

Definition at line 765 of file asioServer.cpp.

References rnp::PacketError::errorCode, rnp::Serializer::getData(), rnp::PACKET_ERROR, sendPacketImmediate(), rnp::Serializer::serializeError(), rnp::Serializer::serializeHeader(), and rnp::PacketHeader::type.

Referenced by handleConnect(), handleLobbyLeave(), handleLobbyListRequest(), and handleStartGameRequest().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendLobbyCreateResponse()

void srv::AsioServer::sendLobbyCreateResponse ( std::uint32_t sessionId,
std::uint32_t lobbyId,
bool success,
rnp::ErrorCode errorCode = rnp::ErrorCode::INTERNAL_ERROR )
private

Send lobby create response.

Parameters
sessionIdTarget client session ID
lobbyIdCreated lobby ID (0 if failed)
successSuccess status
errorCodeError code if failed

Definition at line 1486 of file asioServer.cpp.

References rnp::PacketLobbyCreateResponse::errorCode, rnp::Serializer::getData(), utl::INFO, rnp::PacketHeader::length, rnp::LOBBY_CREATE_RESPONSE, rnp::PacketLobbyCreateResponse::lobbyId, utl::Logger::log(), m_senderEndpoint, sendPacketImmediate(), rnp::Serializer::serializeHeader(), rnp::Serializer::serializeLobbyCreateResponse(), rnp::PacketHeader::sessionId, rnp::PacketLobbyCreateResponse::success, and rnp::PacketHeader::type.

Referenced by handleLobbyCreate().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendLobbyJoinResponse()

void srv::AsioServer::sendLobbyJoinResponse ( std::uint32_t sessionId,
std::uint32_t lobbyId,
bool success,
rnp::ErrorCode errorCode,
const rnp::LobbyInfo * lobbyInfo = nullptr )
private

Send lobby join response.

Parameters
sessionIdTarget client session ID
lobbyIdTarget lobby ID
successSuccess status
errorCodeError code if failed
lobbyInfoLobby information if successful

Send lobby join response to client

Parameters
sessionIdRequesting client's session ID
lobbyIdTarget lobby ID
successWhether join succeeded
errorCodeError code if failed
lobbyInfoCurrent lobby info (if success)

Definition at line 1511 of file asioServer.cpp.

References rnp::PacketLobbyJoinResponse::errorCode, rnp::Serializer::getData(), utl::INFO, rnp::PacketHeader::length, rnp::LOBBY_JOIN_RESPONSE, rnp::PacketLobbyJoinResponse::lobbyId, rnp::PacketLobbyJoinResponse::lobbyInfo, utl::Logger::log(), m_senderEndpoint, sendPacketImmediate(), rnp::Serializer::serializeHeader(), rnp::Serializer::serializeLobbyJoinResponse(), rnp::PacketHeader::sessionId, rnp::PacketLobbyJoinResponse::success, and rnp::PacketHeader::type.

Referenced by handleLobbyJoin().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendLobbyList()

void srv::AsioServer::sendLobbyList ( std::uint32_t sessionId)
private

Send lobby list to client.

Parameters
sessionIdTarget client session ID

Send lobby list to requesting client

Parameters
sessionIdRequesting client's session ID

Definition at line 1173 of file asioServer.cpp.

References rnp::LobbyInfo::currentPlayers, rnp::Serializer::getData(), utl::INFO, rnp::PacketHeader::length, rnp::PacketLobbyListResponse::lobbies, rnp::LOBBY_LIST_RESPONSE, rnp::PacketLobbyListResponse::lobbyCount, rnp::LobbyInfo::lobbyId, lobbyToLobbyInfo(), utl::Logger::log(), m_lobbies, m_lobbiesMutex, m_senderEndpoint, rnp::LobbyInfo::maxPlayers, sendPacketImmediate(), rnp::Serializer::serializeHeader(), rnp::Serializer::serializeLobbyListResponse(), rnp::PacketHeader::sessionId, and rnp::PacketHeader::type.

Referenced by handleLobbyListRequest().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendPacketImmediate()

void srv::AsioServer::sendPacketImmediate ( const std::vector< std::uint8_t > & data,
const asio::ip::udp::endpoint & destination )
private

Send packet immediately.

Parameters
dataPacket data
destinationTarget endpoint

Definition at line 531 of file asioServer.cpp.

References utl::INFO, utl::Logger::log(), m_running, m_socket, m_socketMutex, and utl::WARNING.

Referenced by broadcastGameOverToLobby(), broadcastGameStart(), broadcastLobbyUpdate(), disconnectClient(), processSendQueue(), sendConnectAccept(), sendError(), sendLobbyCreateResponse(), sendLobbyJoinResponse(), sendLobbyList(), sendPong(), and stop().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendPong()

void srv::AsioServer::sendPong ( std::uint32_t nonce,
const asio::ip::udp::endpoint & destination,
std::uint32_t sessionId )
private

Send PONG response.

Parameters
noncePing nonce
destinationTarget endpoint
sessionIdClient session ID

Definition at line 717 of file asioServer.cpp.

References rnp::Serializer::getData(), rnp::PacketPingPong::nonce, rnp::PONG, sendPacketImmediate(), rnp::Serializer::serializeHeader(), rnp::Serializer::serializePingPong(), and rnp::PacketHeader::type.

Referenced by handlePing().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendToAllClients()

void srv::AsioServer::sendToAllClients ( const std::vector< std::uint8_t > & data,
bool reliable = false )
overridevirtual

Implements srv::INetworkServer.

Definition at line 237 of file asioServer.cpp.

References m_clients, m_clientsMutex, m_sendQueue, and m_sendQueueMutex.

Referenced by handleBroadcastEvent(), and handleSendEntityEventToClients().

+ Here is the caller graph for this function:

◆ sendToClient()

void srv::AsioServer::sendToClient ( std::uint32_t sessionId,
const std::vector< std::uint8_t > & data,
bool reliable = false )
overridevirtual

Implements srv::INetworkServer.

Definition at line 222 of file asioServer.cpp.

References m_clients, m_clientsMutex, m_sendQueue, and m_sendQueueMutex.

Referenced by handleSendToClientEvent().

+ Here is the caller graph for this function:

◆ setServerCapabilities()

void srv::AsioServer::setServerCapabilities ( std::uint32_t caps)
overridevirtual

Implements srv::INetworkServer.

Definition at line 336 of file asioServer.cpp.

References m_serverCaps.

◆ setTickRate()

void srv::AsioServer::setTickRate ( std::uint16_t tickRate)
overridevirtual

Implements srv::INetworkServer.

Definition at line 330 of file asioServer.cpp.

References m_tickRate.

◆ setupPacketHandlers()

void srv::AsioServer::setupPacketHandlers ( )
private

◆ start()

void srv::AsioServer::start ( )
overridevirtual

Implements srv::INetworkServer.

Definition at line 60 of file asioServer.cpp.

References m_host, m_networkThread, m_port, m_running, m_socket, m_started, networkThreadLoop(), and startReceive().

+ Here is the call graph for this function:

◆ startReceive()

void srv::AsioServer::startReceive ( )
private

Start receiving packets asynchronously.

Start asynchronous receive operation

Initiates async_receive_from on the UDP socket

Definition at line 388 of file asioServer.cpp.

References utl::Logger::log(), m_recvBuffer, m_running, m_senderEndpoint, m_socket, and utl::WARNING.

Referenced by start().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ stop()

◆ update()

void srv::AsioServer::update ( )
overridevirtual

Implements srv::INetworkServer.

Definition at line 206 of file asioServer.cpp.

References m_running, processEventBusEvents(), processSendQueue(), and updateClientManagement().

Referenced by broadcastLobbyUpdate().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ updateClientManagement()

void srv::AsioServer::updateClientManagement ( )
private

Update client timeouts and send pings.

Update client management (timeouts, pings)

Checks for timed-out clients and sends periodic ping packets

Definition at line 785 of file asioServer.cpp.

References disconnectClient(), rnp::Serializer::getData(), m_clients, m_clientsMutex, m_clientTimeout, m_lastPingTime, m_pingInterval, m_sendQueue, m_sendQueueMutex, rnp::PacketPingPong::nonce, rnp::PING, rnp::Serializer::serializeHeader(), rnp::Serializer::serializePingPong(), and rnp::PacketHeader::type.

Referenced by update().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Member Data Documentation

◆ m_clients

◆ m_clientsMutex

◆ m_clientTimeout

std::chrono::milliseconds srv::AsioServer::m_clientTimeout
private

Client timeout duration (15000ms)

Definition at line 232 of file AsioServer.hpp.

Referenced by updateClientManagement().

◆ m_componentId

std::uint32_t srv::AsioServer::m_componentId
private

Component ID for event bus registration.

Definition at line 235 of file AsioServer.hpp.

Referenced by AsioServer(), handleConnect(), handleDisconnect(), handleEntityEvent(), handleStartGameRequest(), and processEventBusEvents().

◆ m_endpointToSession

std::unordered_map<std::string, std::uint32_t> srv::AsioServer::m_endpointToSession
private

Map of endpoint string to session ID.

Definition at line 210 of file AsioServer.hpp.

Referenced by disconnectClient(), handleConnect(), handleDisconnect(), and stop().

◆ m_eventBus

◆ m_host

std::string srv::AsioServer::m_host
private

Server bind address (e.g., "0.0.0.0")

Definition at line 198 of file AsioServer.hpp.

Referenced by init(), and start().

◆ m_ioContext

std::unique_ptr<asio::io_context> srv::AsioServer::m_ioContext
private

ASIO I/O context for async operations.

Definition at line 193 of file AsioServer.hpp.

Referenced by networkThreadLoop(), and stop().

◆ m_lastPingTime

std::chrono::steady_clock::time_point srv::AsioServer::m_lastPingTime
private

Timestamp of last ping sweep.

Definition at line 230 of file AsioServer.hpp.

Referenced by updateClientManagement().

◆ m_lobbies

std::unordered_map<std::uint32_t, Lobby> srv::AsioServer::m_lobbies
private

◆ m_lobbiesMutex

std::mutex srv::AsioServer::m_lobbiesMutex
mutableprivate

◆ m_networkThread

std::unique_ptr<std::thread> srv::AsioServer::m_networkThread
private

Dedicated network thread.

Definition at line 195 of file AsioServer.hpp.

Referenced by start(), and stop().

◆ m_nextLobbyId

std::uint32_t srv::AsioServer::m_nextLobbyId
private

Next available lobby ID.

Definition at line 216 of file AsioServer.hpp.

Referenced by createLobby(), and handleLobbyCreate().

◆ m_nextSessionId

std::uint32_t srv::AsioServer::m_nextSessionId
private

Next available session ID.

Definition at line 211 of file AsioServer.hpp.

◆ m_packetHandler

std::unique_ptr<rnp::HandlerPacket> srv::AsioServer::m_packetHandler
private

RNP packet handler instance.

Definition at line 220 of file AsioServer.hpp.

Referenced by disconnectClient(), handleReceive(), and setupPacketHandlers().

◆ m_pingInterval

std::chrono::milliseconds srv::AsioServer::m_pingInterval
private

Interval between ping sweeps (5000ms)

Definition at line 231 of file AsioServer.hpp.

Referenced by updateClientManagement().

◆ m_port

std::uint16_t srv::AsioServer::m_port
private

Server listening port (default: 4567)

Definition at line 199 of file AsioServer.hpp.

Referenced by init(), and start().

◆ m_recvBuffer

std::array<std::uint8_t, MAX_LEN_RECV_BUFFER> srv::AsioServer::m_recvBuffer
private

Buffer for receiving UDP packets.

Definition at line 226 of file AsioServer.hpp.

Referenced by handleReceive(), and startReceive().

◆ m_running

std::atomic<bool> srv::AsioServer::m_running
private

Server running state (atomic for thread safety)

Definition at line 204 of file AsioServer.hpp.

Referenced by isRunning(), networkThreadLoop(), sendPacketImmediate(), start(), startReceive(), stop(), and update().

◆ m_senderEndpoint

asio::ip::udp::endpoint srv::AsioServer::m_senderEndpoint
private

◆ m_sendQueue

std::queue<QueuedPacket> srv::AsioServer::m_sendQueue
private

Queue of packets waiting to be sent.

Definition at line 221 of file AsioServer.hpp.

Referenced by processSendQueue(), sendToAllClients(), sendToClient(), and updateClientManagement().

◆ m_sendQueueMutex

std::mutex srv::AsioServer::m_sendQueueMutex
private

Mutex for send queue access.

Definition at line 222 of file AsioServer.hpp.

Referenced by processSendQueue(), sendToAllClients(), sendToClient(), and updateClientManagement().

◆ m_serverCaps

std::uint32_t srv::AsioServer::m_serverCaps
private

Server capability flags.

Definition at line 201 of file AsioServer.hpp.

Referenced by sendConnectAccept(), and setServerCapabilities().

◆ m_socket

std::unique_ptr<asio::ip::udp::socket> srv::AsioServer::m_socket
private

UDP socket for network communication.

Definition at line 194 of file AsioServer.hpp.

Referenced by sendPacketImmediate(), start(), startReceive(), and stop().

◆ m_socketMutex

std::mutex srv::AsioServer::m_socketMutex
private

Mutex for socket operations.

Definition at line 223 of file AsioServer.hpp.

Referenced by sendPacketImmediate(), and stop().

◆ m_started

std::atomic<bool> srv::AsioServer::m_started
private

Server started state.

Definition at line 205 of file AsioServer.hpp.

Referenced by start(), and stop().

◆ m_tickRate

std::uint16_t srv::AsioServer::m_tickRate
private

Server tick rate in Hz.

Definition at line 200 of file AsioServer.hpp.

Referenced by sendConnectAccept(), and setTickRate().


The documentation for this class was generated from the following files: