R-Type
Networked shoot'em up built on Aegis2D
Loading...
Searching...
No Matches
rtype::ServerNetwork Class Reference

The two ports the server listens on, and the TCP side of the sessions. More...

#include </__w/project-rtype/project-rtype/server/include/rtype/server_network.hpp>

Public Types

using Clock = std::chrono::steady_clock
 Clock of the login and UDP timeouts.
 
using PlayerHandler = std::function< void(const Session &session)>
 Called with a session that joins the game.
 
using LeaveHandler = std::function< void(const Session &session, LeaveReason reason)>
 Called with a session that leaves the game, and why: Left for a Logout, a Disconnect or a closed TCP connection, TimedOut for a silent player or one that acknowledges no event, Kicked for a protocol error.
 
using InputHandler = std::function< void(const Session &session, aegis2d::ecs::PlayerInput input, std::uint16_t sequence)>
 Called with the actions a player holds and the sequence of the Input they come from, its most recent one.
 

Public Member Functions

 ServerNetwork (aegis2d::net::NetworkContext &context, std::uint16_t tcp_port, std::uint16_t udp_port, SessionTable sessions=SessionTable{})
 Listens on both ports, on every IPv4 interface.
 
 ServerNetwork (const ServerNetwork &)=delete
 
ServerNetwork & operator= (const ServerNetwork &)=delete
 
 ServerNetwork (ServerNetwork &&)=delete
 
ServerNetwork & operator= (ServerNetwork &&)=delete
 
 ~ServerNetwork ()=default
 
void on_players (PlayerHandler joined, LeaveHandler left)
 Sets what to do when a player joins or leaves the game.
 
void on_input (InputHandler input)
 Sets what to do with the inputs of the players.
 
void set_compression (std::optional< std::size_t > threshold) noexcept
 Sets from which size the payloads of snapshots and events are compressed.
 
std::variant< std::size_t, ChatRejection > say (std::string_view text)
 Sends a message of the server to every session logged in (ChatMessage with server_player and server_name, RFC section 3.8).
 
std::size_t close_room (std::uint32_t room)
 Closes a room: each of its sessions gets Logout with RoomClosed and ends; the others of the game are told it was kicked.
 
std::optional< aegis2d::net::Endpoint > remove_player (std::string_view name, LogoutReason reason)
 Removes a player for the administrator: it gets Logout with reason, every other session a message of the server saying so, and its game a PlayerLeft with Kicked.
 
void set_bans (BanList *bans) noexcept
 Sets the bans checked at each login: a banned address gets LoginRejected with Banned.
 
BanList * bans () const noexcept
 The bans checked at each login.
 
void set_scoreboard (const Scoreboard *board) noexcept
 Sets the board a ListScores reads (RFC section 3.9).
 
void set_waves (std::vector< std::string > names)
 Sets the waves files a room may be created with (SessionTable::set_waves()).
 
std::optional< std::size_t > compression () const noexcept
 From which size payloads are compressed.
 
void send_snapshot (std::span< const std::vector< std::byte > > payloads, std::uint32_t room, const std::shared_ptr< const Snapshot > &snapshot=nullptr)
 Sends a snapshot to every player of a room whose endpoint is bound.
 
void send_snapshot (const std::shared_ptr< const Snapshot > &snapshot, std::uint32_t room)
 Sends a snapshot to every player of a room whose endpoint is bound, encoded against the latest snapshot that player acknowledged.
 
std::uint64_t snapshots_sent () const noexcept
 Number of Snapshot datagrams sent, all players together.
 
void send_events (std::span< const std::vector< std::byte > > events, std::uint32_t room, std::optional< std::uint32_t > token=std::nullopt)
 Sends gameplay events, reliably, to the players of a room whose endpoint is bound.
 
void send_events_to_others (std::span< const std::vector< std::byte > > events, std::uint32_t room, std::uint32_t token)
 Sends gameplay events, reliably, to every bound player of a room but one, as send_events().
 
std::uint64_t event_datagrams_sent () const noexcept
 Number of Event datagrams sent, first sends and resends, all players together.
 
void update (Clock::time_point now)
 Ends the sessions of the bound players silent for udp_timeout, closes the connections that did not log in within login_timeout and those whose rejection or Logout is sent, then forgets the closed ones; resends the events that are due.
 
void set_limits (RateLimits limits)
 Sets the limits on the traffic of one address (RFC section 6.6).
 
void shutdown ()
 Starts a clean stop of the server (RFC section 3.2).
 
bool idle () const noexcept
 Tells whether every connection is closed and forgotten, after shutdown().
 
aegis2d::net::Endpoint tcp_endpoint () const
 Local TCP address and port, with the port the system picked if 0 was asked.
 
aegis2d::net::Endpoint udp_endpoint () const
 Local UDP address and port, with the port the system picked if 0 was asked.
 
const SessionTable & sessions () const noexcept
 Sessions open.
 
std::uint64_t connections () const noexcept
 Number of TCP connections accepted.
 
std::size_t open_connections () const noexcept
 Number of TCP connections not removed yet by update(), logged in or not.
 
std::uint64_t datagrams () const noexcept
 Number of UDP datagrams received, oversized ones excluded.
 
std::uint64_t rate_limited () const noexcept
 Number of UDP datagrams dropped because their address sent too many.
 
std::uint64_t refused_connections () const noexcept
 Number of TCP connections closed at once, their address having too many open.
 
std::uint64_t dropped_datagrams () const noexcept
 Number of UDP datagrams dropped for their header, direction or source.
 
std::uint64_t game_datagrams () const noexcept
 Number of valid datagrams from bound endpoints, other than Connect.
 
std::uint64_t timeouts () const noexcept
 Number of sessions ended because their player sent nothing for udp_timeout.
 
std::uint64_t errors () const noexcept
 Number of datagrams and TCP messages whose handling threw.
 
const aegis2d::net::TrafficCounters * traffic (std::uint32_t token) const
 Datagrams exchanged with a bound player, by direction and packet type.
 
const aegis2d::net::RttEstimator * rtt (std::uint32_t token) const
 Round trip time to a bound player, with its jitter.
 
const SnapshotHistory * snapshots (std::uint32_t token) const
 The last snapshots sent to a player and the ones it acknowledged.
 

Static Public Attributes

static constexpr std::chrono::seconds login_timeout {5}
 Time a new connection has to send its LoginRequest.
 
static constexpr std::chrono::seconds udp_timeout {5}
 Time a bound player may send no valid datagram before its session is lost (RFC section 5.5).
 
static constexpr std::chrono::seconds traffic_report_period {10}
 Time between two lines of traffic and round trip time of each bound player in the log.
 

Detailed Description

The two ports the server listens on, and the TCP side of the sessions.

Binds both ports in its constructor, so a port already in use stops the server at start. Each TCP connection must log in (RFC section 3.3): a valid LoginRequest opens a session and gets LoginAccepted; a refused one gets LoginRejected and is closed once it is sent; a connection that sends anything else first, or nothing within login_timeout, is closed without a reply (section 6.5). Once logged in, a ListRooms gets the RoomList of the rooms in use and a CreateRoom its RoomCreated or RoomRejected (section 3.6); a JoinRoom gets RoomJoined or JoinRejected, a LeaveRoom moves the session to the lobby and a SetReady sets whether it is ready (section 3.7); a ChatSend whose text and rate pass (check_chat_text(), ChatRate) goes as a ChatMessage to every session of the sender's room, or of the lobby, the sender included, and any other gets ChatRejected with its reason (section 3.8); a Logout or the closing of the connection ends the session; any other message is a protocol error that ends it too. Whenever the sessions of a room or their ready states change, the clients of that room that sent a message of the rooms and are not in game get its RoomPlayers, then GameStart once every session of the room out of game is ready.

Each datagram is checked as RFC section 6.3 says (header, direction, source). A Connect with an empty payload and the token of a session binds its source endpoint to the session and is answered with Accept, again for each Connect from that endpoint (section 3.4). Every other datagram must come from a bound endpoint with the token of its session, and a payload as its type requires: one byte of actions for Input, nothing for Heartbeat and Disconnect, a well-framed list for Event (whose events are ignored, as only the server sends events). Datagrams that fail a check are dropped without an answer and counted; the others are acknowledged in the next datagram sent to the player. The most recent Input goes to on_input(); a Disconnect ends the session like a Logout. A bound player that sends no valid datagram for udp_timeout has lost its session (RFC section 5.5): it gets Logout with the reason TimedOut, its connection is closed once it is sent, and it leaves the game.

Each session belongs to a room (Session::room): snapshots and events go to the players of one room only, so the games of several rooms run side by side without seeing each other.

The handling of each datagram and TCP message is contained: an exception is logged, the client that sent the packet is kicked (Logout with the reason ProtocolError, then Kicked for the game, RFC section 6.6), and the sockets go on serving the others.

Connections and datagrams are handled on the thread running the context; update() runs the timeouts and removes closed connections. Create, use and destroy it on that thread, or while the context is not running.

Member Typedef Documentation

◆ Clock

using rtype::ServerNetwork::Clock = std::chrono::steady_clock

Clock of the login and UDP timeouts.

◆ InputHandler

using rtype::ServerNetwork::InputHandler = std::function<void(const Session& session, aegis2d::ecs::PlayerInput input, std::uint16_t sequence)>

Called with the actions a player holds and the sequence of the Input they come from, its most recent one.

◆ LeaveHandler

using rtype::ServerNetwork::LeaveHandler = std::function<void(const Session& session, LeaveReason reason)>

Called with a session that leaves the game, and why: Left for a Logout, a Disconnect or a closed TCP connection, TimedOut for a silent player or one that acknowledges no event, Kicked for a protocol error.

◆ PlayerHandler

using rtype::ServerNetwork::PlayerHandler = std::function<void(const Session& session)>

Called with a session that joins the game.

Constructor & Destructor Documentation

◆ ServerNetwork() [1/3]

rtype::ServerNetwork::ServerNetwork ( aegis2d::net::NetworkContext &  context,
std::uint16_t  tcp_port,
std::uint16_t  udp_port,
SessionTable  sessions = SessionTable{} 
)

Listens on both ports, on every IPv4 interface.

Parameters
contextContext that runs the sockets; it must outlive this object.
tcp_portTCP port of the logins, or 0 for any free port.
udp_portUDP port of the game, or 0 for any free port.
sessionsSessions to fill, empty, with their rooms (SessionTable::set_rooms()); tests give one with a seed.
Exceptions
aegis2d::net::SocketErrorIf a port is already in use or cannot be bound.

◆ ServerNetwork() [2/3]

rtype::ServerNetwork::ServerNetwork ( const ServerNetwork &  )
delete

◆ ServerNetwork() [3/3]

rtype::ServerNetwork::ServerNetwork ( ServerNetwork &&  )
delete

◆ ~ServerNetwork()

rtype::ServerNetwork::~ServerNetwork ( )
default

Member Function Documentation

◆ bans()

BanList * rtype::ServerNetwork::bans ( ) const
noexcept

The bans checked at each login.

Returns
The list given to set_bans(), or nullptr.

◆ close_room()

std::size_t rtype::ServerNetwork::close_room ( std::uint32_t  room)

Closes a room: each of its sessions gets Logout with RoomClosed and ends; the others of the game are told it was kicked.

Parameters
roomNumber of the room.
Returns
The number of sessions ended, 0 if the room was empty or not in use.

◆ compression()

std::optional< std::size_t > rtype::ServerNetwork::compression ( ) const
noexcept

From which size payloads are compressed.

Returns
The threshold set by set_compression(), or std::nullopt.

◆ connections()

std::uint64_t rtype::ServerNetwork::connections ( ) const
noexcept

Number of TCP connections accepted.

Returns
The count since the construction.

◆ datagrams()

std::uint64_t rtype::ServerNetwork::datagrams ( ) const
noexcept

Number of UDP datagrams received, oversized ones excluded.

Returns
The count since the construction.

◆ dropped_datagrams()

std::uint64_t rtype::ServerNetwork::dropped_datagrams ( ) const
noexcept

Number of UDP datagrams dropped for their header, direction or source.

Returns
The count since the construction.

◆ errors()

std::uint64_t rtype::ServerNetwork::errors ( ) const
noexcept

Number of datagrams and TCP messages whose handling threw.

Returns
The count since the construction.

◆ event_datagrams_sent()

std::uint64_t rtype::ServerNetwork::event_datagrams_sent ( ) const
noexcept

Number of Event datagrams sent, first sends and resends, all players together.

Returns
The count since the construction.

◆ game_datagrams()

std::uint64_t rtype::ServerNetwork::game_datagrams ( ) const
noexcept

Number of valid datagrams from bound endpoints, other than Connect.

Returns
The count since the construction.

◆ idle()

bool rtype::ServerNetwork::idle ( ) const
noexcept

Tells whether every connection is closed and forgotten, after shutdown().

Returns
true when no TCP connection is left.

◆ on_input()

void rtype::ServerNetwork::on_input ( InputHandler  input)

Sets what to do with the inputs of the players.

Called for each input of a valid Input datagram from a bound endpoint that is more recent than the last one passed on (by its sequence, InputRecord), oldest first: an input whose datagram was lost is passed on when one of the next three arrives; those passed on already, late ones and malformed datagrams are not (RFC section 4.2).

Parameters
inputCalled with the session, the actions it holds and their sequence.

◆ on_players()

void rtype::ServerNetwork::on_players ( PlayerHandler  joined,
LeaveHandler  left 
)

Sets what to do when a player joins or leaves the game.

A session joins once its UDP endpoint is bound (its first Accept), so a client that cannot reach the UDP port never appears in the game. It leaves when it ends (Logout, Disconnect, TCP closed, UDP timeout, protocol error), if it had joined.

Parameters
joinedCalled with the session, its endpoint bound.
leftCalled with the session and why it ended, once it is forgotten.

◆ open_connections()

std::size_t rtype::ServerNetwork::open_connections ( ) const
noexcept

Number of TCP connections not removed yet by update(), logged in or not.

Returns
The count.

◆ operator=() [1/2]

ServerNetwork & rtype::ServerNetwork::operator= ( const ServerNetwork &  )
delete

◆ operator=() [2/2]

ServerNetwork & rtype::ServerNetwork::operator= ( ServerNetwork &&  )
delete

◆ rate_limited()

std::uint64_t rtype::ServerNetwork::rate_limited ( ) const
noexcept

Number of UDP datagrams dropped because their address sent too many.

Returns
The count since the construction.

◆ refused_connections()

std::uint64_t rtype::ServerNetwork::refused_connections ( ) const
noexcept

Number of TCP connections closed at once, their address having too many open.

Returns
The count since the construction.

◆ remove_player()

std::optional< aegis2d::net::Endpoint > rtype::ServerNetwork::remove_player ( std::string_view  name,
LogoutReason  reason 
)

Removes a player for the administrator: it gets Logout with reason, every other session a message of the server saying so, and its game a PlayerLeft with Kicked.

Parameters
nameName of the player.
reasonLogoutReason::Kicked or LogoutReason::Banned.
Returns
The address its TCP connection comes from, or std::nullopt if no player has this name.

◆ rtt()

const aegis2d::net::RttEstimator * rtype::ServerNetwork::rtt ( std::uint32_t  token) const

Round trip time to a bound player, with its jitter.

A sample each time a datagram of the player acknowledges, for the first time, one sent to it (Accept, Snapshot, Event). It includes the time the client waits before its next datagram: in game, at most its input interval (about 17 ms). update() logs it every traffic_report_period.

Parameters
tokenSession of the player.
Returns
Its estimate, or nothing if the session is not bound or has ended.

◆ say()

std::variant< std::size_t, ChatRejection > rtype::ServerNetwork::say ( std::string_view  text)

Sends a message of the server to every session logged in (ChatMessage with server_player and server_name, RFC section 3.8).

Parameters
textText to send, checked as a chat text.
Returns
The number of sessions it was sent to, or ChatRejection::TooLong or BadText.

◆ send_events()

void rtype::ServerNetwork::send_events ( std::span< const std::vector< std::byte > >  events,
std::uint32_t  room,
std::optional< std::uint32_t >  token = std::nullopt 
)

Sends gameplay events, reliably, to the players of a room whose endpoint is bound.

Each event is queued on the player's channel, which numbers it and resends it until it is acknowledged (RFC section 5.3): the events leave at once in Event datagrams, the resends in update(). A player who leaves net::max_events_in_flight events unacknowledged is lost (RFC section 6.2): its session ends.

Parameters
eventsEvents from write_event(), in order.
roomRoom of the game the events come from (Session::room).
tokenOnly to this session of the room, for a player who joins (RFC section 4.6); to every bound player of the room by default.

◆ send_events_to_others()

void rtype::ServerNetwork::send_events_to_others ( std::span< const std::vector< std::byte > >  events,
std::uint32_t  room,
std::uint32_t  token 
)

Sends gameplay events, reliably, to every bound player of a room but one, as send_events().

For the PlayerJoined of a player who joins, which the others get (RFC section 4.6).

Parameters
eventsEvents from write_event(), in order.
roomRoom of the game the events come from (Session::room).
tokenSession that does not get them.

◆ send_snapshot() [1/2]

void rtype::ServerNetwork::send_snapshot ( const std::shared_ptr< const Snapshot > &  snapshot,
std::uint32_t  room 
)

Sends a snapshot to every player of a room whose endpoint is bound, encoded against the latest snapshot that player acknowledged.

write_delta_snapshot() encodes it against snapshots()'s latest acknowledged one, or whole if there is none; the payloads go as with the other overload, and the snapshot is kept in the player's snapshots().

Parameters
snapshotThe snapshot to send; nothing is sent if it is nullptr.
roomRoom of the game the snapshot comes from (Session::room).
Exceptions
std::invalid_argumentif a field does not fit, as write_delta_snapshot().

◆ send_snapshot() [2/2]

void rtype::ServerNetwork::send_snapshot ( std::span< const std::vector< std::byte > >  payloads,
std::uint32_t  room,
const std::shared_ptr< const Snapshot > &  snapshot = nullptr 
)

Sends a snapshot to every player of a room whose endpoint is bound.

Each payload goes in its own Snapshot datagram, whose header takes the next sequence of the player's channel and acknowledges its datagrams (RFC 5.1).

Parameters
payloadsPayloads from write_snapshot(), header excluded.
roomRoom of the game the snapshot comes from (Session::room).
snapshotThe snapshot they encode, to keep in each player's snapshots() with the sequences of its datagrams; none by default.

◆ sessions()

const SessionTable & rtype::ServerNetwork::sessions ( ) const
noexcept

Sessions open.

Returns
The table of the logged-in players.

◆ set_bans()

void rtype::ServerNetwork::set_bans ( BanList *  bans)
noexcept

Sets the bans checked at each login: a banned address gets LoginRejected with Banned.

Parameters
bansThe list, which must outlive this object, or nullptr for none.

◆ set_compression()

void rtype::ServerNetwork::set_compression ( std::optional< std::size_t >  threshold)
noexcept

Sets from which size the payloads of snapshots and events are compressed.

A payload of at least threshold bytes is sent compressed with LZ4 when that makes it smaller (aegis2d/net/compression.hpp, RFC section 2.6). Whatever this setting, compressed datagrams received are decompressed.

Parameters
thresholdSize in bytes, or std::nullopt (the default) to never compress.

◆ set_limits()

void rtype::ServerNetwork::set_limits ( RateLimits  limits)

Sets the limits on the traffic of one address (RFC section 6.6).

Datagrams past RateLimits::datagrams_per_second in a second are dropped before any other check, and a connection past RateLimits::connections_per_address open ones is closed at once. Defaults: 300 datagrams per second, 8 connections.

Parameters
limitsNew limits; the counts so far are forgotten.

◆ set_scoreboard()

void rtype::ServerNetwork::set_scoreboard ( const Scoreboard *  board)
noexcept

Sets the board a ListScores reads (RFC section 3.9).

Parameters
boardThe best scores, which must outlive this object, or nullptr to answer with none.

◆ set_waves()

void rtype::ServerNetwork::set_waves ( std::vector< std::string >  names)

Sets the waves files a room may be created with (SessionTable::set_waves()).

Parameters
namesTheir names, without .json.

◆ shutdown()

void rtype::ServerNetwork::shutdown ( )

Starts a clean stop of the server (RFC section 3.2).

Stops accepting connections, sends Logout with the reason Shutdown to every logged-in player and ends its session, and closes the connections that did not log in. Each connection closes once its Logout has left: keep running the context and update() until idle().

◆ snapshots()

const SnapshotHistory * rtype::ServerNetwork::snapshots ( std::uint32_t  token) const

The last snapshots sent to a player and the ones it acknowledged.

Every valid datagram of the player acknowledges the server's datagrams it received (ack, ack_bits): a snapshot is acknowledged once all its datagrams are.

Parameters
tokenSession of the player.
Returns
Its history, or nothing if the session is not bound or has ended.

◆ snapshots_sent()

std::uint64_t rtype::ServerNetwork::snapshots_sent ( ) const
noexcept

Number of Snapshot datagrams sent, all players together.

Returns
The count since the construction.

◆ tcp_endpoint()

aegis2d::net::Endpoint rtype::ServerNetwork::tcp_endpoint ( ) const

Local TCP address and port, with the port the system picked if 0 was asked.

Returns
The bound endpoint.

◆ timeouts()

std::uint64_t rtype::ServerNetwork::timeouts ( ) const
noexcept

Number of sessions ended because their player sent nothing for udp_timeout.

Returns
The count since the construction.

◆ traffic()

const aegis2d::net::TrafficCounters * rtype::ServerNetwork::traffic ( std::uint32_t  token) const

Datagrams exchanged with a bound player, by direction and packet type.

Counts the datagrams sent to the player (Accept, Snapshot, Event) and the valid ones received from it, since its endpoint was bound; update() logs them every traffic_report_period.

Parameters
tokenSession of the player.
Returns
Its counters, or nothing if the session is not bound or has ended.

◆ udp_endpoint()

aegis2d::net::Endpoint rtype::ServerNetwork::udp_endpoint ( ) const

Local UDP address and port, with the port the system picked if 0 was asked.

Returns
The bound endpoint.

◆ update()

void rtype::ServerNetwork::update ( Clock::time_point  now)

Ends the sessions of the bound players silent for udp_timeout, closes the connections that did not log in within login_timeout and those whose rejection or Logout is sent, then forgets the closed ones; resends the events that are due.

Call it regularly, a few times per second at least.

Parameters
nowCurrent time.

Member Data Documentation

◆ login_timeout

constexpr std::chrono::seconds rtype::ServerNetwork::login_timeout {5}
staticconstexpr

Time a new connection has to send its LoginRequest.

◆ traffic_report_period

constexpr std::chrono::seconds rtype::ServerNetwork::traffic_report_period {10}
staticconstexpr

Time between two lines of traffic and round trip time of each bound player in the log.

◆ udp_timeout

constexpr std::chrono::seconds rtype::ServerNetwork::udp_timeout {5}
staticconstexpr

Time a bound player may send no valid datagram before its session is lost (RFC section 5.5).


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