r-type  0.0.0
R-Type main
Loading...
Searching...
No Matches
AsioServer.hpp
Go to the documentation of this file.
1///
2/// @file AsioServer.hpp
3/// @brief Asio-based UDP server implementation for R-Type multiplayer game networking
4/// @details This file provides a complete UDP server implementation using ASIO library.
5/// It handles client connections, packet routing, lobby management, and game state synchronization.
6/// The server implements the R-Type Network Protocol (RNP) specification.
7/// @namespace srv
8/// @author R-Type Team
9/// @date 2025
10///
11
12#pragma once
13
17#include "Utils/Event.hpp"
18#include "Utils/EventBus.hpp"
19
20#include <asio.hpp>
21#include <atomic>
22#include <memory>
23#include <mutex>
24#include <queue>
25#include <thread>
26#include <unordered_map>
27#include <vector>
28
29namespace srv
30{
31
32 ///
33 /// @struct ClientSession
34 /// @brief Represents an active client connection session
35 /// @details Stores all relevant information about a connected client including
36 /// network endpoint, authentication state, latency metrics, and lobby membership.
37 ///
39 {
40 std::uint32_t sessionId; ///< Unique session identifier assigned by server
41 asio::ip::udp::endpoint endpoint; ///< Client's network endpoint (IP:port)
42 std::chrono::steady_clock::time_point lastSeen; ///< Timestamp of last received packet
43 std::string playerName; ///< Player's display name
44 std::uint32_t clientCaps; ///< Client capability flags (reserved)
45 bool isConnected; ///< Connection state flag
46 std::uint32_t lastPingSent; ///< Nonce of last PING packet sent
47 std::uint32_t latency; ///< Round-trip time in milliseconds
48 std::uint32_t currentLobbyId; ///< ID of joined lobby, 0 if not in lobby
49
50 ///
51 /// @brief Default constructor
52 /// @details Initializes a client session with default values
53 ///
55 : sessionId(0), lastSeen(std::chrono::steady_clock::now()), clientCaps(0), isConnected(false),
57 {
58 }
59 };
60
61 ///
62 /// @enum LobbyStatus
63 /// @brief Status codes for lobby operations
64 /// @details Used to indicate the result of lobby-related operations
65 ///
66 enum class LobbyStatus : std::uint8_t
67 {
68 SUCCESS = 0, ///< Operation completed successfully
69 WAITING = 1, ///< Lobby is waiting for players
70 IN_GAME = 2, ///< Game in progress
71 NOT_FOUND = 3, ///< Requested lobby does not exist
72 FULL = 4, ///< Lobby has reached maximum capacity
73 ALREADY_IN_LOBBY = 5 ///< Client is already in a lobby
74 };
75
76 ///
77 /// @struct Lobby
78 /// @brief Represents a game lobby (room) where players gather before starting a game
79 /// @details Contains all lobby metadata including players, host, game mode, and status.
80 /// Lobbies are managed by the server and synchronized across all members.
81 ///
82 struct Lobby
83 {
84 std::uint32_t lobbyId; ///< Unique lobby identifier
85 std::string lobbyName; ///< Human-readable lobby name
86 std::uint32_t hostSessionId; ///< Session ID of the lobby host
87 std::vector<std::uint32_t> playerSessions; ///< List of player session IDs in this lobby
88 std::uint8_t maxPlayers; ///< Maximum number of players allowed (1-8)
89 std::uint8_t gameMode; ///< Game mode identifier
90 rnp::LobbyStatus status; ///< Current lobby status
91 std::chrono::steady_clock::time_point createdTime; ///< Timestamp when lobby was created
92
93 ///
94 /// @brief Default constructor
95 /// @details Creates an empty lobby with default values
96 ///
99 status(rnp::LobbyStatus::WAITING), createdTime(std::chrono::steady_clock::now())
100 {
101 }
102
103 ///
104 /// @brief Parameterized constructor
105 /// @param id Unique lobby identifier
106 /// @param name Lobby display name
107 /// @param host Session ID of the host player
108 /// @param max Maximum number of players (1-8)
109 /// @param mode Game mode identifier
110 ///
111 Lobby(std::uint32_t id, const std::string &name, std::uint32_t host, std::uint8_t max, std::uint8_t mode)
112 : lobbyId(id), lobbyName(name), hostSessionId(host), maxPlayers(max), gameMode(mode),
113 status(rnp::LobbyStatus::WAITING), createdTime(std::chrono::steady_clock::now())
114 {
115 }
116 };
117
118 ///
119 /// @struct QueuedPacket
120 /// @brief Represents a packet queued for asynchronous transmission
121 /// @details Used in the send queue to buffer outgoing packets before transmission
122 ///
124 {
125 std::vector<std::uint8_t> data; ///< Serialized packet data
126 asio::ip::udp::endpoint destination; ///< Target endpoint
127 bool reliable; ///< Whether packet requires reliable delivery
128
129 ///
130 /// @brief Constructor
131 /// @param d Packet data buffer
132 /// @param dest Destination endpoint
133 /// @param rel Reliability flag (default: false)
134 ///
135 QueuedPacket(const std::vector<std::uint8_t> &d, const asio::ip::udp::endpoint &dest, bool rel = false)
136 : data(d), destination(dest), reliable(rel)
137 {
138 }
139 };
140
141 ///
142 /// @class AsioServer
143 /// @brief High-performance UDP server implementation using ASIO library
144 /// @details This class provides a complete multiplayer game server implementation with:
145 /// - Asynchronous UDP networking
146 /// - Client session management
147 /// - Lobby system for matchmaking
148 /// - Packet routing and handling
149 /// - Event bus integration
150 /// - Thread-safe operations
151 ///
152 /// The server runs its network operations on a separate thread and communicates
153 /// with the game engine via an event bus system.
154 ///
155 /// @namespace srv
156 ///
157 class AsioServer final : public INetworkServer
158 {
159
160 public:
161 ///
162 /// @brief Constructor
163 ///
164 AsioServer();
165
166 ///
167 /// @brief Destructor
168 ///
169 ~AsioServer() override;
170
171 [[nodiscard]] const std::string getName() const override { return "Network_Asio_Server"; }
172 [[nodiscard]] utl::PluginType getType() const override { return utl::PluginType::NETWORK_CLIENT; }
173
174 // INetworkServer implementation
175 void init(const std::string &host, std::uint16_t port) override;
176 void start() override;
177 void stop() override;
178 void update() override;
179 void sendToClient(std::uint32_t sessionId, const std::vector<std::uint8_t> &data,
180 bool reliable = false) override;
181 void sendToAllClients(const std::vector<std::uint8_t> &data, bool reliable = false) override;
182 void disconnectClient(std::uint32_t sessionId) override;
183
184 [[nodiscard]] std::size_t getClientCount() const override;
185 [[nodiscard]] std::vector<std::uint32_t> getConnectedSessions() const override;
186 [[nodiscard]] bool isRunning() const override;
187
188 void setTickRate(std::uint16_t tickRate) override;
189 void setServerCapabilities(std::uint32_t caps) override;
190
191 private:
192 // Network components
193 std::unique_ptr<asio::io_context> m_ioContext; ///< ASIO I/O context for async operations
194 std::unique_ptr<asio::ip::udp::socket> m_socket; ///< UDP socket for network communication
195 std::unique_ptr<std::thread> m_networkThread; ///< Dedicated network thread
196
197 // Server configuration
198 std::string m_host; ///< Server bind address (e.g., "0.0.0.0")
199 std::uint16_t m_port; ///< Server listening port (default: 4567)
200 std::uint16_t m_tickRate; ///< Server tick rate in Hz
201 std::uint32_t m_serverCaps; ///< Server capability flags
202
203 // Server state
204 std::atomic<bool> m_running; ///< Server running state (atomic for thread safety)
205 std::atomic<bool> m_started; ///< Server started state
206
207 // Client management
208 std::unordered_map<std::uint32_t, ClientSession> m_clients; ///< Map of session ID to client session
209 std::unordered_map<std::string, std::uint32_t>
210 m_endpointToSession; ///< Map of endpoint string to session ID
211 std::uint32_t m_nextSessionId; ///< Next available session ID
212 mutable std::mutex m_clientsMutex; ///< Mutex for thread-safe client access
213
214 // Lobby management
215 std::unordered_map<std::uint32_t, Lobby> m_lobbies; ///< Map of lobby ID to lobby data
216 std::uint32_t m_nextLobbyId; ///< Next available lobby ID
217 mutable std::mutex m_lobbiesMutex; ///< Mutex for thread-safe lobby access
218
219 // Packet handling
220 std::unique_ptr<rnp::HandlerPacket> m_packetHandler; ///< RNP packet handler instance
221 std::queue<QueuedPacket> m_sendQueue; ///< Queue of packets waiting to be sent
222 std::mutex m_sendQueueMutex; ///< Mutex for send queue access
223 std::mutex m_socketMutex; ///< Mutex for socket operations
224
225 // Reception buffer
226 std::array<std::uint8_t, MAX_LEN_RECV_BUFFER> m_recvBuffer; ///< Buffer for receiving UDP packets
227 asio::ip::udp::endpoint m_senderEndpoint; ///< Endpoint of last packet sender
228
229 // Timing
230 std::chrono::steady_clock::time_point m_lastPingTime; ///< Timestamp of last ping sweep
231 std::chrono::milliseconds m_pingInterval; ///< Interval between ping sweeps (5000ms)
232 std::chrono::milliseconds m_clientTimeout; ///< Client timeout duration (15000ms)
233
234 // EventBus
235 std::uint32_t m_componentId; ///< Component ID for event bus registration
237
238 ///
239 /// @brief Initialize packet handlers
240 ///
241 ///
242 /// @brief Setup packet handlers for all RNP packet types
243 /// @details Registers callback functions for each packet type with the packet handler
244 ///
245 void setupPacketHandlers();
246
247 ///
248 /// @brief Start receiving packets asynchronously
249 ///
250 ///
251 /// @brief Start asynchronous receive operation
252 /// @details Initiates async_receive_from on the UDP socket
253 ///
254 void startReceive();
255
256 ///
257 /// @brief Handle received packet
258 /// @param bytesReceived Number of bytes received
259 ///
260 void handleReceive(std::size_t bytesReceived);
261
262 ///
263 /// @brief Network thread main loop
264 ///
265 ///
266 /// @brief Main network thread loop
267 /// @details Runs the ASIO io_context and handles network events
268 ///
269 void networkThreadLoop() const;
270
271 ///
272 /// @brief Generate unique session ID
273 /// @return New session ID
274 ///
275 ///
276 /// @brief Generate a unique session ID
277 /// @return New session ID (cryptographically random)
278 ///
279 std::uint32_t generateSessionId() const;
280
281 ///
282 /// @brief Get endpoint string representation
283 /// @param endpoint UDP endpoint
284 /// @return String representation
285 ///
286 ///
287 /// @brief Convert endpoint to string representation
288 /// @param endpoint UDP endpoint
289 /// @return String in format "IP:PORT"
290 ///
291 std::string endpointToString(const asio::ip::udp::endpoint &endpoint);
292
293 ///
294 /// @brief Send packet immediately
295 /// @param data Packet data
296 /// @param destination Target endpoint
297 ///
298 void sendPacketImmediate(const std::vector<std::uint8_t> &data, const asio::ip::udp::endpoint &destination);
299
300 ///
301 /// @brief Handle CONNECT packet
302 /// @param packet Connect packet
303 /// @param context Packet context
304 /// @return Handler result
305 ///
307
308 ///
309 /// @brief Handle DISCONNECT packet
310 /// @param packet Disconnect packet
311 /// @param context Packet context
312 /// @return Handler result
313 ///
315
316 ///
317 /// @brief Handle PING packet
318 /// @param packet Ping packet
319 /// @param context Packet context
320 /// @return Handler result
321 ///
323
324 ///
325 /// @brief Handle PONG packet
326 /// @param packet Pong packet
327 /// @param context Packet context
328 /// @return Handler result
329 ///
331
332 ///
333 /// @brief Send PONG response
334 /// @param nonce Ping nonce
335 /// @param destination Target endpoint
336 /// @param sessionId Client session ID
337 ///
338 void sendPong(std::uint32_t nonce, const asio::ip::udp::endpoint &destination, std::uint32_t sessionId);
339
340 ///
341 /// @brief Send CONNECT_ACCEPT response
342 /// @param sessionId New session ID
343 /// @param destination Target endpoint
344 ///
345 void sendConnectAccept(std::uint32_t sessionId, const asio::ip::udp::endpoint &destination);
346
347 ///
348 /// @brief Send ERROR packet
349 /// @param errorCode Error code
350 /// @param description Error description
351 /// @param destination Target endpoint
352 /// @param sessionId Session ID
353 ///
354 void sendError(rnp::ErrorCode errorCode, const std::string &description,
355 const asio::ip::udp::endpoint &destination, std::uint32_t sessionId);
356
357 ///
358 /// @brief Update client timeouts and send pings
359 ///
360 ///
361 /// @brief Update client management (timeouts, pings)
362 /// @details Checks for timed-out clients and sends periodic ping packets
363 ///
365
366 ///
367 /// @brief Process send queue
368 ///
369 ///
370 /// @brief Process outgoing packet queue
371 /// @details Sends all queued packets via UDP socket
372 ///
373 void processSendQueue();
374
375 ///
376 /// @brief Process EventBus events for network operations
377 ///
378 ///
379 /// @brief Process events from the event bus
380 /// @details Handles events from game engine (sends, broadcasts, etc.)
381 ///
383
384 ///
385 /// @brief Handle send to client event from EventBus
386 /// @param event Send to client event
387 ///
388 ///
389 /// @brief Handle "send to client" event from event bus
390 /// @param event Event containing target session and packet data
391 ///
392 void handleSendToClientEvent(const utl::Event &event);
393
394 ///
395 /// @brief Handle broadcast event from EventBus
396 /// @param event Broadcast event
397 ///
398 ///
399 /// @brief Handle broadcast event from event bus
400 /// @param event Event containing packet data to broadcast
401 ///
402 void handleBroadcastEvent(const utl::Event &event);
403
404 ///
405 /// @brief Handle send entity event to clients from EventBus
406 /// @param event Entity event to send to clients
407 ///
408 ///
409 /// @brief Handle entity event broadcast to clients
410 /// @param event Event containing entity event data
411 ///
413
414 ///
415 /// @brief Handle entity event packet (including player inputs)
416 /// @param events Entity event records
417 /// @param context Packet context
418 /// @return Handler result
419 ///
420 rnp::HandlerResult handleEntityEvent(const std::vector<rnp::EventRecord> &events,
421 const rnp::PacketContext &context) const;
422
423 ///
424 /// @brief Handle LOBBY_LIST_REQUEST packet
425 /// @param context Packet context
426 /// @return Handler result
427 ///
429
430 ///
431 /// @brief Handle LOBBY_CREATE packet
432 /// @param packet Lobby create packet
433 /// @param context Packet context
434 /// @return Handler result
435 ///
437 const rnp::PacketContext &context);
438
439 ///
440 /// @brief Handle LOBBY_JOIN packet
441 /// @param packet Lobby join packet
442 /// @param context Packet context
443 /// @return Handler result
444 ///
446
447 ///
448 /// @brief Handle LOBBY_LEAVE packet
449 /// @param context Packet context
450 /// @return Handler result
451 ///
453
454 ///
455 /// @brief Send lobby list to client
456 /// @param sessionId Target client session ID
457 ///
458 ///
459 /// @brief Send lobby list to requesting client
460 /// @param sessionId Requesting client's session ID
461 ///
462 void sendLobbyList(std::uint32_t sessionId);
463
464 ///
465 /// @brief Create new lobby
466 /// @param name Lobby name
467 /// @param hostSession Host session ID
468 /// @param maxPlayers Maximum players
469 /// @param gameMode Game mode
470 /// @return New lobby ID
471 ///
472 ///
473 /// @brief Create a new lobby
474 /// @param lobbyName Display name for the lobby
475 /// @param hostSessionId Session ID of the lobby host
476 /// @param maxPlayers Maximum number of players (1-8)
477 /// @param gameMode Game mode identifier
478 /// @return New lobby ID
479 ///
480 std::uint32_t createLobby(const std::string &lobbyName, std::uint32_t hostSessionId,
481 std::uint8_t maxPlayers, std::uint8_t gameMode);
482
483 ///
484 /// @brief Join player to lobby
485 /// @param lobbyId Target lobby ID
486 /// @param sessionId Player session ID
487 /// @return Success status
488 ///
489 ///
490 /// @brief Join an existing lobby
491 /// @param lobbyId Target lobby ID
492 /// @param sessionId Joining client's session ID
493 /// @return Status code indicating success or failure reason
494 ///
495 LobbyStatus joinLobby(std::uint32_t lobbyId, std::uint32_t sessionId);
496
497 ///
498 /// @brief Remove player from lobby
499 /// @param sessionId Player session ID
500 ///
501 ///
502 /// @brief Remove a client from their current lobby
503 /// @param sessionId Client's session ID
504 ///
505 void leaveLobby(std::uint32_t sessionId);
506
507 ///
508 /// @brief Broadcast lobby update to all lobby members
509 /// @param lobbyId Target lobby ID
510 ///
511 ///
512 /// @brief Broadcast lobby update to all lobby members
513 /// @param lobbyId Lobby ID to broadcast update for
514 ///
515 void broadcastLobbyUpdate(std::uint32_t lobbyId);
516
517 ///
518 /// @brief Handle START_GAME_REQUEST packet
519 /// @param packet Start game request packet
520 /// @param context Packet context
521 /// @return Handler result
522 ///
524 const rnp::PacketContext &context);
525
526 ///
527 /// @brief Broadcast game start to all players in lobby
528 /// @param lobbyId Target lobby ID
529 ///
530 ///
531 /// @brief Broadcast game start notification to all lobby members
532 /// @param lobbyId Lobby ID that is starting
533 ///
534 ///
535 /// @brief Broadcast game over notification to lobby members
536 /// @param lobbyId Lobby ID that finished
537 ///
538 void broadcastGameOverToLobby(std::uint32_t lobbyId);
539
540 ///
541 /// @brief Broadcast game start notification to all lobby members
542 /// @param lobbyId Lobby ID that is starting
543 ///
544 void broadcastGameStart(std::uint32_t lobbyId);
545
546 ///
547 /// @brief Convert Lobby to LobbyInfo for network transmission
548 /// @param lobby Lobby structure
549 /// @return LobbyInfo structure
550 ///
551 ///
552 /// @brief Convert internal Lobby struct to RNP LobbyInfo
553 /// @param lobby Internal lobby structure
554 /// @return RNP protocol lobby info structure
555 ///
557
558 ///
559 /// @brief Send lobby create response
560 /// @param sessionId Target client session ID
561 /// @param lobbyId Created lobby ID (0 if failed)
562 /// @param success Success status
563 /// @param errorCode Error code if failed
564 ///
565 void sendLobbyCreateResponse(std::uint32_t sessionId, std::uint32_t lobbyId, bool success,
567
568 ///
569 /// @brief Send lobby join response
570 /// @param sessionId Target client session ID
571 /// @param lobbyId Target lobby ID
572 /// @param success Success status
573 /// @param errorCode Error code if failed
574 /// @param lobbyInfo Lobby information if successful
575 ///
576 ///
577 /// @brief Send lobby join response to client
578 /// @param sessionId Requesting client's session ID
579 /// @param lobbyId Target lobby ID
580 /// @param success Whether join succeeded
581 /// @param errorCode Error code if failed
582 /// @param lobbyInfo Current lobby info (if success)
583 ///
584 void sendLobbyJoinResponse(std::uint32_t sessionId, std::uint32_t lobbyId, bool success,
585 rnp::ErrorCode errorCode, const rnp::LobbyInfo *lobbyInfo = nullptr);
586
587 ///
588 /// @brief Handle GAME_OVER event from game server
589 /// @param event Game over event
590 ///
591 ///
592 /// @brief Handle game over event from game engine
593 /// @param event Event containing game over data
594 ///
595 void handleGameOverEvent(const utl::Event &event);
596
597 ///
598 /// @brief Broadcast GAME_OVER packet to all players in a lobby
599 /// @param lobbyId Target lobby ID
600 /// @param gameOverData Game over packet data
601 ///
602 void broadcastGameOverToLobby(std::uint32_t lobbyId, const std::vector<std::uint8_t> &gameOverData);
603
604 ///
605 /// @brief Clean up empty lobbies
606 ///
607 ///
608 /// @brief Remove empty lobbies from server
609 /// @details Called periodically to clean up abandoned lobbies
610 ///
611 void cleanupEmptyLobbies();
612 };
613
614} // namespace srv
Thread-safe event bus implementation for inter-component communication.
Event structures and types for event-driven communication.
Network packet handler for RNP protocol.
This file contains the server network interface.
This file contains the network protocol.
High-performance UDP server implementation using ASIO library.
std::uint16_t m_tickRate
Server tick rate in Hz.
rnp::HandlerResult handlePing(const rnp::PacketPingPong &packet, const rnp::PacketContext &context)
Handle PING packet.
std::unique_ptr< asio::io_context > m_ioContext
ASIO I/O context for async operations.
rnp::HandlerResult handleLobbyJoin(const rnp::PacketLobbyJoin &packet, const rnp::PacketContext &context)
Handle LOBBY_JOIN packet.
void init(const std::string &host, std::uint16_t port) override
void disconnectClient(std::uint32_t sessionId) override
void setupPacketHandlers()
Initialize packet handlers.
void sendToClient(std::uint32_t sessionId, const std::vector< std::uint8_t > &data, bool reliable=false) override
rnp::HandlerResult handleEntityEvent(const std::vector< rnp::EventRecord > &events, const rnp::PacketContext &context) const
Handle entity event packet (including player inputs)
void cleanupEmptyLobbies()
Clean up empty lobbies.
std::uint32_t m_nextLobbyId
Next available lobby ID.
void update() override
rnp::HandlerResult handleConnect(const rnp::PacketConnect &packet, const rnp::PacketContext &context)
Handle CONNECT packet.
~AsioServer() override
Destructor.
void sendConnectAccept(std::uint32_t sessionId, const asio::ip::udp::endpoint &destination)
Send CONNECT_ACCEPT response.
std::string m_host
Server bind address (e.g., "0.0.0.0")
void handleReceive(std::size_t bytesReceived)
Handle received packet.
rnp::LobbyInfo lobbyToLobbyInfo(const Lobby &lobby)
Convert Lobby to LobbyInfo for network transmission.
void setServerCapabilities(std::uint32_t caps) override
void setTickRate(std::uint16_t tickRate) override
std::string endpointToString(const asio::ip::udp::endpoint &endpoint)
Get endpoint string representation.
std::vector< std::uint32_t > getConnectedSessions() const override
rnp::HandlerResult handlePong(const rnp::PacketPingPong &packet, const rnp::PacketContext &context)
Handle PONG packet.
bool isRunning() const override
std::unique_ptr< std::thread > m_networkThread
Dedicated network thread.
std::atomic< bool > m_started
Server started state.
void startReceive()
Start receiving packets asynchronously.
void handleGameOverEvent(const utl::Event &event)
Handle GAME_OVER event from game server.
asio::ip::udp::endpoint m_senderEndpoint
Endpoint of last packet sender.
void sendError(rnp::ErrorCode errorCode, const std::string &description, const asio::ip::udp::endpoint &destination, std::uint32_t sessionId)
Send ERROR packet.
LobbyStatus joinLobby(std::uint32_t lobbyId, std::uint32_t sessionId)
Join player to lobby.
void sendPong(std::uint32_t nonce, const asio::ip::udp::endpoint &destination, std::uint32_t sessionId)
Send PONG response.
std::unordered_map< std::uint32_t, ClientSession > m_clients
Map of session ID to client session.
void networkThreadLoop() const
Network thread main loop.
std::chrono::milliseconds m_clientTimeout
Client timeout duration (15000ms)
std::uint16_t m_port
Server listening port (default: 4567)
std::mutex m_sendQueueMutex
Mutex for send queue access.
std::uint32_t m_serverCaps
Server capability flags.
std::uint32_t m_nextSessionId
Next available session ID.
void sendPacketImmediate(const std::vector< std::uint8_t > &data, const asio::ip::udp::endpoint &destination)
Send packet immediately.
std::uint32_t createLobby(const std::string &lobbyName, std::uint32_t hostSessionId, std::uint8_t maxPlayers, std::uint8_t gameMode)
Create new lobby.
std::mutex m_lobbiesMutex
Mutex for thread-safe lobby access.
void broadcastGameStart(std::uint32_t lobbyId)
Broadcast game start notification to all lobby members.
void sendLobbyCreateResponse(std::uint32_t sessionId, std::uint32_t lobbyId, bool success, rnp::ErrorCode errorCode=rnp::ErrorCode::INTERNAL_ERROR)
Send lobby create response.
std::mutex m_socketMutex
Mutex for socket operations.
AsioServer()
Constructor.
void handleBroadcastEvent(const utl::Event &event)
Handle broadcast event from EventBus.
std::mutex m_clientsMutex
Mutex for thread-safe client access.
std::unordered_map< std::uint32_t, Lobby > m_lobbies
Map of lobby ID to lobby data.
std::queue< QueuedPacket > m_sendQueue
Queue of packets waiting to be sent.
rnp::HandlerResult handleLobbyCreate(const rnp::PacketLobbyCreate &packet, const rnp::PacketContext &context)
Handle LOBBY_CREATE packet.
rnp::HandlerResult handleLobbyListRequest(const rnp::PacketContext &context)
Handle LOBBY_LIST_REQUEST packet.
utl::PluginType getType() const override
std::atomic< bool > m_running
Server running state (atomic for thread safety)
std::array< std::uint8_t, MAX_LEN_RECV_BUFFER > m_recvBuffer
Buffer for receiving UDP packets.
void start() override
void sendToAllClients(const std::vector< std::uint8_t > &data, bool reliable=false) override
std::uint32_t m_componentId
Component ID for event bus registration.
void broadcastLobbyUpdate(std::uint32_t lobbyId)
Broadcast lobby update to all lobby members.
void processSendQueue()
Process send queue.
std::unordered_map< std::string, std::uint32_t > m_endpointToSession
Map of endpoint string to session ID.
const std::string getName() const override
rnp::HandlerResult handleLobbyLeave(const rnp::PacketContext &context)
Handle LOBBY_LEAVE packet.
void updateClientManagement()
Update client timeouts and send pings.
rnp::HandlerResult handleDisconnect(const rnp::PacketDisconnect &packet, const rnp::PacketContext &context)
Handle DISCONNECT packet.
std::unique_ptr< asio::ip::udp::socket > m_socket
UDP socket for network communication.
std::chrono::milliseconds m_pingInterval
Interval between ping sweeps (5000ms)
void leaveLobby(std::uint32_t sessionId)
Remove player from lobby.
void sendLobbyJoinResponse(std::uint32_t sessionId, std::uint32_t lobbyId, bool success, rnp::ErrorCode errorCode, const rnp::LobbyInfo *lobbyInfo=nullptr)
Send lobby join response.
std::chrono::steady_clock::time_point m_lastPingTime
Timestamp of last ping sweep.
std::size_t getClientCount() const override
void stop() override
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 handleSendToClientEvent(const utl::Event &event)
Handle send to client event from EventBus.
std::unique_ptr< rnp::HandlerPacket > m_packetHandler
RNP packet handler instance.
void sendLobbyList(std::uint32_t sessionId)
Send lobby list to client.
void processEventBusEvents()
Process EventBus events for network operations.
void handleSendEntityEventToClients(const utl::Event &event)
Handle send entity event to clients from EventBus.
utl::EventBus & m_eventBus
std::uint32_t generateSessionId() const
Generate unique session ID.
Interface for the server network.
Thread-safe event bus for decoupled component communication.
Definition EventBus.hpp:31
Event structure for inter-component communication.
Definition Event.hpp:89
ErrorCode
Error codes.
Definition Protocol.hpp:75
HandlerResult
Packet processing result.
LobbyStatus
Lobby status enumeration.
Definition Protocol.hpp:227
unsigned int id
Definition IScene.hpp:16
LobbyStatus
Status codes for lobby operations.
@ IN_GAME
Game in progress.
@ WAITING
Lobby is waiting for players.
@ NOT_FOUND
Requested lobby does not exist.
@ FULL
Lobby has reached maximum capacity.
@ SUCCESS
Operation completed successfully.
@ ALREADY_IN_LOBBY
Client is already in a lobby.
PluginType
Definition IPlugin.hpp:22
Lobby information structure.
Definition Protocol.hpp:237
CONNECT packet payload.
Definition Protocol.hpp:138
Context information for packet processing.
DISCONNECT packet payload.
Definition Protocol.hpp:159
LOBBY_CREATE packet payload.
Definition Protocol.hpp:261
LOBBY_JOIN packet payload.
Definition Protocol.hpp:282
PING/PONG packet payload.
Definition Protocol.hpp:208
START_GAME_REQUEST packet payload (client requests to start game)
Definition Protocol.hpp:317
Represents an active client connection session.
std::uint32_t currentLobbyId
ID of joined lobby, 0 if not in lobby.
bool isConnected
Connection state flag.
std::chrono::steady_clock::time_point lastSeen
Timestamp of last received packet.
std::uint32_t clientCaps
Client capability flags (reserved)
std::uint32_t sessionId
Unique session identifier assigned by server.
std::string playerName
Player's display name.
std::uint32_t lastPingSent
Nonce of last PING packet sent.
asio::ip::udp::endpoint endpoint
Client's network endpoint (IP:port)
std::uint32_t latency
Round-trip time in milliseconds.
ClientSession()
Default constructor.
Represents a game lobby (room) where players gather before starting a game.
std::uint32_t hostSessionId
Session ID of the lobby host.
Lobby(std::uint32_t id, const std::string &name, std::uint32_t host, std::uint8_t max, std::uint8_t mode)
Parameterized constructor.
rnp::LobbyStatus status
Current lobby status.
std::uint8_t maxPlayers
Maximum number of players allowed (1-8)
std::vector< std::uint32_t > playerSessions
List of player session IDs in this lobby.
std::uint32_t lobbyId
Unique lobby identifier.
std::string lobbyName
Human-readable lobby name.
std::uint8_t gameMode
Game mode identifier.
std::chrono::steady_clock::time_point createdTime
Timestamp when lobby was created.
Lobby()
Default constructor.
Represents a packet queued for asynchronous transmission.
bool reliable
Whether packet requires reliable delivery.
asio::ip::udp::endpoint destination
Target endpoint.
std::vector< std::uint8_t > data
Serialized packet data.
QueuedPacket(const std::vector< std::uint8_t > &d, const asio::ip::udp::endpoint &dest, bool rel=false)
Constructor.