group2 0.1.0
CSE 125 Group 2
Loading...
Searching...
No Matches
Server.hpp
Go to the documentation of this file.
1
3
4#pragma once
5
13#include "network/ShotEvent.hpp"
16
17#include <SDL3/SDL_stdinc.h>
18
19#include <SDL3_net/SDL_net.h>
20#include <atomic>
21#include <deque>
22#include <entt/entity/entity.hpp>
23#include <mutex>
24#include <thread>
25#include <vector>
26
31class Server
32{
33public:
41 bool init(const char* addr, Uint16 port, const TransportConfig& transport = {});
42
44 void shutdown();
45
52 void poll() {}
53
56 bool isEmpty();
57
61
64 bool notifyPlayerClientId(ClientId clientId, entt::entity playerEntity);
65
67 void broadcastRegistry(const Registry& registry);
68
70 void broadcastParticleEvents(const std::vector<NetParticleEvent>& events);
71
74 int getClientCount();
75
82 uint16_t getClientRttMs(ClientId clientId);
83
86
88 void broadcastKillEvents(const std::vector<NetKillEvent>& events);
89
98 void flushAllOutbound();
99
100private:
103 {
107
115
125
133 uint32_t connectionId = 0;
134
141
147
153
158 {
159 uint16_t sequence;
161 std::vector<uint8_t> framed;
162 };
163 std::deque<PendingReliableEvent> reliableQueue;
164
175 uint16_t lastReportedRttMs = 0;
176 };
177
182 void handleMessage(Connection& client, const void* data, Uint32 len);
183
185 void acceptClients();
186
189 void disconnectClient(Connection conn);
190
192 void readClients();
193
196
201 bool enqueueTo(const ClientId& clientId, uint8_t replaceKey, const void* data, int len);
202
205 void enqueueBroadcast(uint8_t replaceKey, const void* data, int len);
206
216 void enqueueReliableEvent(const void* data, int len);
217
226 void networkLoop();
227
235 void handleUdpUnreliable(uint32_t connId, const net::UdpEndpointAddr& from, const uint8_t* payload, uint32_t len);
236
237 NET_Server* server = nullptr;
238
239 std::unordered_map<ClientId, Connection> clients;
241
243
244 // ── Phase 3d: UDP sidecar ─────────────────────────────────────────────
245 //
246 // Bound during init() to the same port as the TCP listener (different
247 // protocol = different socket; OS demuxes). The network thread polls
248 // both. Server-assigned 32-bit connection IDs let us match an
249 // incoming UDP datagram to a TCP-established Connection — the IDs
250 // are minted on TCP accept and shipped to the client in the
251 // ASSIGN_CLIENT_ID packet so it can stamp them on outbound UDP.
254 std::unordered_map<uint32_t, ClientId> connIdToClient_;
255
256 // ── Stage 3b: dedicated network thread ────────────────────────────────
257 //
258 // The mutex protects every member above (clients map, eventQueue,
259 // nextClientId, NET_Server*) — both the game thread (enqueueTo /
260 // enqueueBroadcast / dequeueEvent / notifyPlayerClientId) and the
261 // network thread (acceptClients / readClients / flushAllOutbound) hold
262 // it during state mutation. Lock holds are kept short (one phase at a
263 // time) so the game thread isn't starved.
264 std::mutex stateMutex_;
265 std::thread networkThread_;
266 std::atomic<bool> shouldStop_{false};
267};
Network client identifier component for multiplayer entities.
Thread-safe event queue for passing network events to the game loop.
Shared definitions for match status and state synchronization between server and clients.
Length-prefixed message framing layer over a TCP stream socket.
Network configuration loaded from config.toml at startup.
Per-client outbound message queue with replace-on-stale semantics.
Player status manager for things like life state and healing.
Shared ECS registry type alias for the game engine.
entt::registry Registry
Shared ECS registry type alias.
Definition Registry.hpp:11
Wire-format particle effect event broadcast from server to all clients.
Thin wrapper over SDL3_net's NET_DatagramSocket.
FIFO queue of gameplay events awaiting processing each tick.
Definition EventQueue.hpp:11
A single gameplay event produced by network input processing.
Definition Event.hpp:10
Length-prefixed framing layer over a TCP stream socket.
Definition MessageStream.hpp:29
Per-connection outbound message queue.
Definition OutboundQueue.hpp:65
TCP stream socket — receives client packets and echoes them back.
Definition Server.hpp:32
void broadcastParticleEvents(const std::vector< NetParticleEvent > &events)
Broadcast particle events to all clients for effect replication.
Definition Server.cpp:606
bool isEmpty()
Check whether the event queue is empty.
Definition Server.cpp:531
Event dequeueEvent()
Remove and return the next event from the queue.
Definition Server.cpp:537
void handleMessage(Connection &client, const void *data, Uint32 len)
Dispatch a single decoded message from a client.
Definition Server.cpp:427
ClientId getNextClientId()
Generate next unique client ID.
Definition Server.cpp:524
void shutdown()
Close the socket and release resources.
Definition Server.cpp:71
void readClients()
Read and process pending messages from all connected clients.
Definition Server.cpp:408
net::UdpEndpoint udpEndpoint_
Definition Server.hpp:252
void acceptClients()
Accept up to one new client connection per call.
Definition Server.cpp:366
std::unordered_map< uint32_t, ClientId > connIdToClient_
UDP connection-id → ClientId lookup.
Definition Server.hpp:254
void handleUdpUnreliable(uint32_t connId, const net::UdpEndpointAddr &from, const uint8_t *payload, uint32_t len)
Dispatch a UDP datagram received with channel == Unreliable.
Definition Server.cpp:187
std::unordered_map< ClientId, Connection > clients
Currently connected clients.
Definition Server.hpp:239
void broadcastKillEvents(const std::vector< NetKillEvent > &events)
Broadcast kill events to clients for kill feed updates.
Definition Server.cpp:647
std::mutex stateMutex_
Definition Server.hpp:264
std::atomic< bool > shouldStop_
Definition Server.hpp:266
std::thread networkThread_
Definition Server.hpp:265
uint16_t getClientRttMs(ClientId clientId)
Phase 6: get this client's most-recently-reported smoothed RTT.
Definition Server.cpp:629
EventQueue eventQueue
Incoming events awaiting processing.
Definition Server.hpp:240
void enqueueReliableEvent(const void *data, int len)
Phase 3d-5: enqueue a reliable event for all clients.
Definition Server.cpp:157
void flushAllOutbound()
Drain every connection's outbound queue to its socket.
Definition Server.cpp:138
void networkLoop()
Network-thread main loop body.
Definition Server.cpp:282
void enqueueBroadcast(uint8_t replaceKey, const void *data, int len)
Enqueue raw data for all currently-connected clients.
Definition Server.cpp:125
TransportConfig transportConfig_
Definition Server.hpp:253
int getClientCount()
Get the number of currently connected clients.
Definition Server.cpp:623
void disconnectClient(Connection conn)
Disconnect a client and clean up resources.
Definition Server.cpp:398
void poll()
No-op since stage 3b moved I/O onto a dedicated network thread.
Definition Server.hpp:52
ClientId nextClientId
Counter for assigning client IDs.
Definition Server.hpp:242
bool enqueueTo(const ClientId &clientId, uint8_t replaceKey, const void *data, int len)
Enqueue raw data for one client.
Definition Server.cpp:114
void broadcastMatchStatus(MatchStatePacket packet)
Broadcast match status updates to clients.
Definition Server.cpp:638
bool notifyPlayerClientId(ClientId clientId, entt::entity playerEntity)
Update client with new entity id.
Definition Server.cpp:544
NET_Server * server
Underlying SDL_net server handle.
Definition Server.hpp:237
bool init(const char *addr, Uint16 port, const TransportConfig &transport={})
Bind a TCP socket to the given address and port.
Definition Server.cpp:21
void broadcastRegistry(const Registry &registry)
Broadcast the full registry state to all clients.
Definition Server.cpp:568
Wraps a NET_DatagramSocket with header-prefixed I/O.
Definition UdpEndpoint.hpp:77
Associates an entity with a connected network client.
Definition ClientId.hpp:10
Definition MatchStatus.hpp:14
Phase 3d-5: pending reliable events, each scheduled for remainingSends more cycles.
Definition Server.hpp:158
uint16_t sequence
Per-channel send sequence.
Definition Server.hpp:159
uint8_t remainingSends
Decremented each send; popped at 0.
Definition Server.hpp:160
std::vector< uint8_t > framed
[PacketType][rest] payload bytes.
Definition Server.hpp:161
Per-client connection state.
Definition Server.hpp:103
bool pendingInitialization
True if waiting for Game to initialize player entity.
Definition Server.hpp:106
std::deque< PendingReliableEvent > reliableQueue
Definition Server.hpp:163
uint16_t reliableNextSequence
Phase 3d-5: per-client outgoing sequence for the reliable event stream over UDP.
Definition Server.hpp:152
uint32_t connectionId
Phase 3d: server-assigned UDP connection ID.
Definition Server.hpp:133
uint16_t lastReportedRttMs
Phase 6: client's most-recent self-reported smoothed RTT in milliseconds.
Definition Server.hpp:175
uint32_t lastAppliedInputTick
Highest InputSnapshot.tick this client has had applied to the simulation.
Definition Server.hpp:114
OutboundQueue outbound
Per-client userspace outbound queue (Phase 3a).
Definition Server.hpp:124
net::UdpEndpointAddr udpAddr
Phase 3d: source address of the most-recent UDP packet from this client.
Definition Server.hpp:140
uint16_t udpSnapshotSequence
Phase 3d-4: per-client outgoing sequence for the Unreliable channel's snapshot stream.
Definition Server.hpp:146
ClientId clientId
Unique identifier assigned on accept.
Definition Server.hpp:105
MessageStream msgStream
Framed message stream for this client.
Definition Server.hpp:104
Phase 3d: per-feature toggles for the UDP transport rollout.
Definition NetworkConfig.hpp:44
A UDP datagram address (server's view of a remote peer).
Definition UdpEndpoint.hpp:49