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