Leviathan  0.8.0.0
Leviathan game engine
Leviathan::NetworkServerInterface Class Reference

Class that encapsulates common networking functionality required by server programs. More...

#include <NetworkServerInterface.h>

+ Inheritance diagram for Leviathan::NetworkServerInterface:

Public Member Functions

DLLEXPORT NetworkServerInterface (int maxplayers, const std::string &servername, SERVER_JOIN_RESTRICT restricttype=SERVER_JOIN_RESTRICT::Localhost, int additionalflags=0)
 Initializes some values to defaults and requires others to be provided by the subclass that inherits from this. More...
 
virtual DLLEXPORT ~NetworkServerInterface ()
 Default destructor. More...
 
virtual DLLEXPORT void HandleRequestPacket (const std::shared_ptr< NetworkRequest > &request, Connection &connection) override
 Called by ConnectionInfo to handle incoming packets. More...
 
virtual DLLEXPORT void HandleResponseOnlyPacket (const std::shared_ptr< NetworkResponse > &message, Connection &connection) override
 Called by ConnectionInfo when it receives a response without a matching request object. More...
 
DLLEXPORT void TickIt () override
 Updates status of the status of the server's clients. More...
 
DLLEXPORT std::shared_ptr< ConnectedPlayerGetPlayerForConnection (Connection &connection)
 Gets corresponding player from a connection. More...
 
virtual DLLEXPORT std::vector< std::shared_ptr< Connection > > & GetClientConnections () override
 If this is a server returns all the clients. More...
 
DLLEXPORT void RespondToServerStatusRequest (std::shared_ptr< NetworkRequest > request, Connection &connectiontouse)
 Sends a response to a NETWORKREQUESTTYPE_SERVERSTATUS. More...
 
DLLEXPORT void SetServerStatus (SERVER_STATUS newstatus)
 Sets the status of the server to newstatus. More...
 
DLLEXPORT void SetServerAllowPlayers (bool allowingplayers)
 Sets whether the server allows new players. More...
 
virtual DLLEXPORT void CloseDown () override
 Call this before shutting down the server to kick all players properly. More...
 
DLLEXPORT void SendToAllButOnePlayer (const std::shared_ptr< NetworkResponse > &response, Connection *skipme, RECEIVE_GUARANTEE guarantee)
 Sends a response packet to all players except for the player(s) whose connection matches skipme. More...
 
DLLEXPORT void SendToAllPlayers (const std::shared_ptr< NetworkResponse > &response, RECEIVE_GUARANTEE guarantee)
 Sends a response packet to all of the players. More...
 
virtual DLLEXPORT void VerifyWorldIsSyncedWithPlayers (std::shared_ptr< GameWorld > world)
 Verifies that all current players are receiving world updates. More...
 
- Public Member Functions inherited from Leviathan::NetworkInterface
DLLEXPORT NetworkInterface (NETWORKED_TYPE type)
 
virtual DLLEXPORT ~NetworkInterface ()
 
virtual DLLEXPORT bool PreHandleResponse (const std::shared_ptr< NetworkResponse > &response, SentNetworkThing *originalrequest, Connection &connection)
 Called by ConnectionInfo to verify that a response is good. More...
 
virtual DLLEXPORT bool CanConnectionTerminate (Connection &connection)
 Called by Connection just before terminating an inactive connection. More...
 
DLLEXPORT void VerifyType (NETWORKED_TYPE type) const
 Asserts if types don't match. More...
 
NetworkHandlerGetOwner ()
 

Protected Member Functions

DLLEXPORT void _HandleServerJoinRequest (std::shared_ptr< NetworkRequest > request, Connection &connection)
 Used to handle server join request packets. More...
 
virtual DLLEXPORT void PlayerPreconnect (Connection &connection, std::shared_ptr< NetworkRequest > joinrequest)
 Called when a player is about to connect. More...
 
virtual DLLEXPORT void _OnPlayerConnected (std::shared_ptr< ConnectedPlayer > newplayer)
 
virtual DLLEXPORT void _OnPlayerDisconnect (std::shared_ptr< ConnectedPlayer > newplayer)
 
virtual DLLEXPORT bool PlayerPotentiallyKicked (ConnectedPlayer *player)
 
virtual DLLEXPORT void _OnCloseDown ()
 
virtual DLLEXPORT void RegisterCustomCommandHandlers (CommandHandler *addhere)
 Called when the application should register custom command handling providers. More...
 
virtual DLLEXPORT bool AllowPlayerConnectVeto (std::shared_ptr< NetworkRequest > request, Connection &connection, std::string &message)
 Called by _HandleServerJoinRequest to allow specific games to disallow players. More...
 
virtual DLLEXPORT std::shared_ptr< GameWorld_GetWorldForJoinTarget (const std::string &options)
 This is called to determine the GameWorld a player should be added to. Return null to disallow joining the world. More...
 
virtual DLLEXPORT GameWorld_GetWorldForEntityMessage (int32_t worldid)
 This needs to lookup a GameWorld for an entity update message by id. More...
 
void _OnReportCloseConnection (std::shared_ptr< ConnectedPlayer > plyptr)
 
void _OnReportPlayerConnected (std::shared_ptr< ConnectedPlayer > plyptr, Connection &connection)
 Internally used to detect when a new player has connected. More...
 
virtual DLLEXPORT void _OnPlayerJoinedWorld (const std::shared_ptr< ConnectedPlayer > &player, const std::shared_ptr< GameWorld > &world)
 Called when a player has joined a world. More...
 
- Protected Member Functions inherited from Leviathan::NetworkInterface
virtual bool _CustomHandleRequestPacket (const std::shared_ptr< NetworkRequest > &request, Connection &connection)
 
virtual bool _CustomHandleResponseOnlyPacket (const std::shared_ptr< NetworkResponse > &message, Connection &connection)
 
DLLEXPORT bool _HandleDefaultRequest (const std::shared_ptr< NetworkRequest > &request, Connection &connectiontosendresult)
 Utility function for subclasses to call for default handling. More...
 
DLLEXPORT bool _HandleDefaultResponseOnly (const std::shared_ptr< NetworkResponse > &message, Connection &connection)
 Utility function for subclasses to call for default handling of non-request responses. More...
 
DLLEXPORT void SetOwner (NetworkHandler *owner)
 

Protected Attributes

std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
 Holds the list of currently connected players. More...
 
std::vector< std::shared_ptr< Connection > > ServerPlayersConnections
 All the connections used in ServerPlayers. More...
 
int MaxPlayers = 20
 Maximum allowed player count. More...
 
std::vector< int > ActiveBots
 Currently active bots. More...
 
std::string ServerName = "Default Name"
 Name displayed in the server list. More...
 
bool AllowJoin = false
 
SERVER_JOIN_RESTRICT JoinRestrict = SERVER_JOIN_RESTRICT::Localhost
 Type of join restriction, defaults to NETWORKRESPONSE_SERVERJOINRESTRICT_NONE. More...
 
SERVER_STATUS ServerStatus = SERVER_STATUS::Starting
 
int ExtraServerFlags = 0
 This can contain anything the specific game wants. More...
 
int CurrentPlayerID = 1000
 Player ID counter for assigning unique ids for all players. More...
 
std::shared_ptr< CommandHandler_CommandHandler = nullptr
 The object used to handle all player submitted commands. More...
 
- Protected Attributes inherited from Leviathan::NetworkInterface
NETWORKED_TYPE OurNetworkType
 
NetworkHandlerOwner = nullptr
 

Detailed Description

Class that encapsulates common networking functionality required by server programs.

More specific version of NetworkInterface and should be included additionally in server network interface classes.

See also
NetworkInterface

Definition at line 24 of file NetworkServerInterface.h.

Constructor & Destructor Documentation

◆ NetworkServerInterface()

DLLEXPORT NetworkServerInterface::NetworkServerInterface ( int  maxplayers,
const std::string &  servername,
SERVER_JOIN_RESTRICT  restricttype = SERVER_JOIN_RESTRICT::Localhost,
int  additionalflags = 0 
)

Initializes some values to defaults and requires others to be provided by the subclass that inherits from this.

These can be later changed with various set functions

Parameters
maxplayersSets the initial maximum player count
servernameSets the server's name visible in various listings
restricttypeControls who can join the server
additionalflagsSets the application specific flags for this server

Definition at line 15 of file NetworkServerInterface.cpp.

17  :
19  MaxPlayers(maxplayers), ServerName(servername), JoinRestrict(restricttype),
20  ExtraServerFlags(additionalflags), _CommandHandler(new CommandHandler(this))
21 {}
int ExtraServerFlags
This can contain anything the specific game wants.
DLLEXPORT NetworkInterface(NETWORKED_TYPE type)
std::string ServerName
Name displayed in the server list.
std::shared_ptr< CommandHandler > _CommandHandler
The object used to handle all player submitted commands.
SERVER_JOIN_RESTRICT JoinRestrict
Type of join restriction, defaults to NETWORKRESPONSE_SERVERJOINRESTRICT_NONE.
int MaxPlayers
Maximum allowed player count.
Handles all commands sent by the players on the server.

◆ ~NetworkServerInterface()

DLLEXPORT NetworkServerInterface::~NetworkServerInterface ( )
virtual

Default destructor.

Definition at line 23 of file NetworkServerInterface.cpp.

24 {
25  // Release the memory //
26  for(auto iter = ServerPlayers.begin(); iter != ServerPlayers.end();) {
27 
28  // We can now report errors here as this needs to be deleted
29  // before engine is released
30  LOG_WARNING("Warning! server quitting while player list has data in it");
31 
32  iter = ServerPlayers.erase(iter);
33  }
34 }
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.
#define LOG_WARNING(x)
Definition: Define.h:82

Member Function Documentation

◆ _GetWorldForEntityMessage()

DLLEXPORT GameWorld * NetworkServerInterface::_GetWorldForEntityMessage ( int32_t  worldid)
protectedvirtual

This needs to lookup a GameWorld for an entity update message by id.

The default implementation always return nullptr

Definition at line 367 of file NetworkServerInterface.cpp.

368 {
369  LOG_WARNING(
370  "NetworkServerInterface: base implementation of _GetWorldForEntityMessage called");
371  return nullptr;
372 }
#define LOG_WARNING(x)
Definition: Define.h:82

◆ _GetWorldForJoinTarget()

DLLEXPORT std::shared_ptr< GameWorld > NetworkServerInterface::_GetWorldForJoinTarget ( const std::string &  options)
protectedvirtual

This is called to determine the GameWorld a player should be added to. Return null to disallow joining the world.

Definition at line 361 of file NetworkServerInterface.cpp.

363 {
364  return nullptr;
365 }

◆ _HandleServerJoinRequest()

DLLEXPORT void NetworkServerInterface::_HandleServerJoinRequest ( std::shared_ptr< NetworkRequest request,
Connection connection 
)
protected

Used to handle server join request packets.

Todo:

Check connection security status

Add basic connection checking and master server authentication check

Definition at line 256 of file NetworkServerInterface.cpp.

258 {
259  if(!AllowJoin) {
260 
261  ResponseServerDisallow response(request->GetIDForResponse(),
262  "Server is not accepting any players at this time",
264 
265  connection.SendPacketToConnection(response);
266  return;
267  }
268 
269  // Check is the player already connected //
270  if(GetPlayerForConnection(connection)) {
271 
272  ResponseServerDisallow response(request->GetIDForResponse(),
273  "You are already connected to this server, disconnect first",
275 
276  connection.SendPacketToConnection(response);
277  return;
278  }
279 
280  // Call this here, so this can potentially kick players for reserved slots //
281  PlayerPreconnect(connection, request);
282 
283  // Check if we can fit a new player //
284  if((int)(ServerPlayers.size() + 1) > MaxPlayers) {
285 
286  std::string plys = Convert::ToString(ServerPlayers.size());
287 
288  ResponseServerDisallow response(request->GetIDForResponse(),
289  "Server is at maximum capacity, " + plys + "/" + plys,
291 
292  connection.SendPacketToConnection(response);
293  return;
294  }
295 
296  // Connection security check //
297  if(connection.GetState() != CONNECTION_STATE::Authenticated) {
298 
299  ResponseServerDisallow response(request->GetIDForResponse(),
300  "Connection state is invalid", NETWORK_RESPONSE_INVALIDREASON::Unauthenticated);
301 
302  connection.SendPacketToConnection(response);
303  return;
304  }
305 
306  // Do something with join restrict things //
307 
308 
309  // Check if the program wants to veto this join //
310  std::string disallowmessage;
311 
312  if(!AllowPlayerConnectVeto(request, connection, disallowmessage)) {
313 
314  ResponseServerDisallow response(request->GetIDForResponse(), disallowmessage,
316 
317  connection.SendPacketToConnection(response);
318  return;
319  }
320 
321  // Player joined! //
322  int newid = ++CurrentPlayerID;
323 
324  ServerPlayers.push_back(
325  std::make_shared<ConnectedPlayer>(Owner->GetConnection(&connection), this, newid));
326 
327  _OnReportPlayerConnected(ServerPlayers.back(), connection);
328 
329  LOG_INFO("NetworkServerInterface: accepted a new player, ID: " + Convert::ToString(newid));
330 
331  // Send connection notification back to the client //
332  auto response = std::make_shared<ResponseServerAllow>(request->GetIDForResponse(),
333  SERVER_ACCEPTED_TYPE::ConnectAccepted, "Allowed, ID: " + Convert::ToString(newid));
334 
336 }
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
#define LOG_INFO(x)
Definition: Define.h:81
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.
DLLEXPORT std::shared_ptr< ConnectedPlayer > GetPlayerForConnection(Connection &connection)
Gets corresponding player from a connection.
CONNECTION_STATE GetState() const
Definition: Connection.h:126
The server has used a custom rule to disallow this.
static std::string ToString(const T &val)
Definition: Convert.h:72
int MaxPlayers
Maximum allowed player count.
virtual DLLEXPORT void PlayerPreconnect(Connection &connection, std::shared_ptr< NetworkRequest > joinrequest)
Called when a player is about to connect.
int CurrentPlayerID
Player ID counter for assigning unique ids for all players.
DLLEXPORT std::shared_ptr< Connection > GetConnection(Connection *directptr) const
Returns a persistent pointer to a connection.
virtual DLLEXPORT bool AllowPlayerConnectVeto(std::shared_ptr< NetworkRequest > request, Connection &connection, std::string &message)
Called by _HandleServerJoinRequest to allow specific games to disallow players.
The client has already connected to the server, and must disconnect before trying again...
Server has accepted your join request.
void _OnReportPlayerConnected(std::shared_ptr< ConnectedPlayer > plyptr, Connection &connection)
Internally used to detect when a new player has connected.
Server has maximum number of players.

◆ _OnCloseDown()

virtual DLLEXPORT void Leviathan::NetworkServerInterface::_OnCloseDown ( )
inlineprotectedvirtual

Definition at line 109 of file NetworkServerInterface.h.

109 {}

◆ _OnPlayerConnected()

DLLEXPORT void NetworkServerInterface::_OnPlayerConnected ( std::shared_ptr< ConnectedPlayer newplayer)
protectedvirtual

Definition at line 338 of file NetworkServerInterface.cpp.

340 {}

◆ _OnPlayerDisconnect()

DLLEXPORT void NetworkServerInterface::_OnPlayerDisconnect ( std::shared_ptr< ConnectedPlayer newplayer)
protectedvirtual

Definition at line 342 of file NetworkServerInterface.cpp.

344 {}

◆ _OnPlayerJoinedWorld()

DLLEXPORT void NetworkServerInterface::_OnPlayerJoinedWorld ( const std::shared_ptr< ConnectedPlayer > &  player,
const std::shared_ptr< GameWorld > &  world 
)
protectedvirtual

Called when a player has joined a world.

Definition at line 377 of file NetworkServerInterface.cpp.

379 {}

◆ _OnReportCloseConnection()

void NetworkServerInterface::_OnReportCloseConnection ( std::shared_ptr< ConnectedPlayer plyptr)
protected

Internally called when a player is about to be deleted

Will call virtual notify functions

Definition at line 381 of file NetworkServerInterface.cpp.

382 {
383  // Close common interfaces that might be using this player //
384 
385  // Make sure player's connection is removed from client connections
386  for(auto iter = ServerPlayersConnections.begin(); iter != ServerPlayersConnections.end();
387  ++iter) {
388  if((*iter) == plyptr->GetConnection()) {
389 
390  ServerPlayersConnections.erase(iter);
391  break;
392  }
393  }
394 
395  Logger::Get()->Info(
396  "NetworkServerInterface: player \"" + plyptr->GetNickname() + "\" disconnected");
397 
398  _OnPlayerDisconnect(plyptr);
399 }
DLLEXPORT void Info(const std::string &data) override
Definition: Logger.cpp:164
virtual DLLEXPORT void _OnPlayerDisconnect(std::shared_ptr< ConnectedPlayer > newplayer)
std::vector< std::shared_ptr< Connection > > ServerPlayersConnections
All the connections used in ServerPlayers.
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106

◆ _OnReportPlayerConnected()

void NetworkServerInterface::_OnReportPlayerConnected ( std::shared_ptr< ConnectedPlayer plyptr,
Connection connection 
)
protected

Internally used to detect when a new player has connected.

Definition at line 401 of file NetworkServerInterface.cpp.

403 {
404  Logger::Get()->Info(
405  "NetworkServerInterface: player \"" + plyptr->GetNickname() + "\" connected");
406 
407  // Make sure player's connection is in client connections
408  ServerPlayersConnections.push_back((plyptr->GetConnection()));
409 
410  _OnPlayerConnected(plyptr);
411 }
DLLEXPORT void Info(const std::string &data) override
Definition: Logger.cpp:164
virtual DLLEXPORT void _OnPlayerConnected(std::shared_ptr< ConnectedPlayer > newplayer)
std::vector< std::shared_ptr< Connection > > ServerPlayersConnections
All the connections used in ServerPlayers.
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106

◆ AllowPlayerConnectVeto()

DLLEXPORT bool NetworkServerInterface::AllowPlayerConnectVeto ( std::shared_ptr< NetworkRequest request,
Connection connection,
std::string &  message 
)
protectedvirtual

Called by _HandleServerJoinRequest to allow specific games to disallow players.

Returns
true to allow join false to disallow join
Parameters
messageThe error message to give back to the player

Definition at line 351 of file NetworkServerInterface.cpp.

353 {
354  return true;
355 }

◆ CloseDown()

DLLEXPORT void NetworkServerInterface::CloseDown ( )
overridevirtual

Call this before shutting down the server to kick all players properly.

Todo:
Actually call this, maybe make this an event listener

Implements Leviathan::NetworkInterface.

Definition at line 195 of file NetworkServerInterface.cpp.

196 {
197 
198  _OnCloseDown();
199 
200  // Prevent new players //
202  AllowJoin = false;
203 
204  for(auto iter = ServerPlayers.begin(); iter != ServerPlayers.end();) {
205 
206  // Kick them //
207  (*iter)->OnKicked("Server closing");
208 
209  iter = ServerPlayers.erase(iter);
210  }
211 
212  _CommandHandler.reset();
213 }
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.
std::shared_ptr< CommandHandler > _CommandHandler
The object used to handle all player submitted commands.

◆ GetClientConnections()

DLLEXPORT std::vector< std::shared_ptr< Leviathan::Connection > > & NetworkServerInterface::GetClientConnections ( )
overridevirtual

If this is a server returns all the clients.

Implements Leviathan::NetworkInterface.

Definition at line 229 of file NetworkServerInterface.cpp.

230 {
232 }
std::vector< std::shared_ptr< Connection > > ServerPlayersConnections
All the connections used in ServerPlayers.

◆ GetPlayerForConnection()

DLLEXPORT std::shared_ptr< ConnectedPlayer > NetworkServerInterface::GetPlayerForConnection ( Connection connection)

Gets corresponding player from a connection.

Returns
Returns a pointer from PlayerList

Definition at line 215 of file NetworkServerInterface.cpp.

217 {
218  // Search through the connections //
219  for(size_t i = 0; i < ServerPlayers.size(); i++) {
220  // Check with the pointer //
221  if(ServerPlayers[i]->IsConnectionYours(&connection))
222  return ServerPlayers[i];
223  }
224 
225  return nullptr;
226 }
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.

◆ HandleRequestPacket()

DLLEXPORT void NetworkServerInterface::HandleRequestPacket ( const std::shared_ptr< NetworkRequest > &  request,
Connection connection 
)
overridevirtual

Called by ConnectionInfo to handle incoming packets.

This function is responsible for interpreting the packet data and generating a response. If the response could take a long time to generate it is recommended to queue a task to the ThreadingManager.

Note
The connection parameter shouldn't be stored directly since it can become invalid after this function returns. Get a shared pointer from NetworkHandler instead

Implements Leviathan::NetworkInterface.

Definition at line 36 of file NetworkServerInterface.cpp.

38 {
39  LEVIATHAN_ASSERT(request, "request is null");
40 
41  if(_HandleDefaultRequest(request, connection))
42  return;
43 
44  switch(request->GetType()) {
46  // Get the matching player //
47  auto ply = GetPlayerForConnection(connection);
48 
49  // Drop it if no matching players //
50  if(!ply)
51  return;
52 
53  // Send a response to the sender //
54  connection.SendPacketToConnection(
55  std::make_shared<ResponseNone>(NETWORK_RESPONSE_TYPE::None),
57 
58  // Extract the command //
59  auto* data = static_cast<RequestRequestCommandExecution*>(request.get());
60 
61  // Execute it //
62  _CommandHandler->QueueCommand(data->Command, ply.get());
63 
64  return;
65  }
67  RespondToServerStatusRequest(request, connection);
68  return;
69  }
71  // Call handling function //
72  LOG_INFO("NetworkServerInterface: player on " +
73  connection.GenerateFormatedAddressString() + " is trying to connect");
74 
75  _HandleServerJoinRequest(request, connection);
76  return;
77  }
79 
80  auto player = GetPlayerForConnection(connection);
81 
82  if(!player) {
83  LOG_WARNING("NetworkServerInterface: got JoinGame from non-player connection");
84 
85  ResponseServerDisallow response(request->GetIDForResponse(), "",
87 
88  connection.SendPacketToConnection(response);
89  return;
90  }
91 
92  auto* data = static_cast<RequestJoinGame*>(request.get());
93 
94  LOG_INFO("NetworkServerInterface: player \"" + player->GetUniqueName() +
95  "\" is joining an active GameWorld (" + data->Options + ")");
96 
97  auto world = _GetWorldForJoinTarget(data->Options);
98 
99  if(!world) {
100  LOG_WARNING(
101  "NetworkServerInterface: no world found with options: " + data->Options);
102 
103  ResponseServerDisallow response(request->GetIDForResponse(),
104  "No valid world to join found",
106 
107  connection.SendPacketToConnection(response);
108  return;
109  }
110 
111  // TODO: make sure that the player is only in one world at a time. Or add some
112  // limitations for staying in multiple worlds at once
113 
114  if(world->IsConnectionInWorld(connection)) {
115  LOG_WARNING("NetworkServerInterface: player is already in world");
116 
117  ResponseServerDisallow response(request->GetIDForResponse(),
118  "Already connected to this world",
120 
121  connection.SendPacketToConnection(response);
122  return;
123  }
124 
125  auto response = std::make_shared<ResponseServerAllow>(
126  request->GetIDForResponse(), SERVER_ACCEPTED_TYPE::Done);
127 
129 
130  world->SetPlayerReceiveWorld(player);
131  _OnPlayerJoinedWorld(player, world);
132  return;
133  }
134  default: break;
135  }
136 
137  if(_CustomHandleRequestPacket(request, connection))
138  return;
139 
140  LOG_ERROR(
141  "NetworkServerInterface: failed to handle request of type: " + request->GetTypeStr());
142 }
virtual DLLEXPORT void _OnPlayerJoinedWorld(const std::shared_ptr< ConnectedPlayer > &player, const std::shared_ptr< GameWorld > &world)
Called when a player has joined a world.
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
#define LOG_INFO(x)
Definition: Define.h:81
#define LOG_ERROR(x)
Definition: Define.h:83
virtual bool _CustomHandleRequestPacket(const std::shared_ptr< NetworkRequest > &request, Connection &connection)
virtual DLLEXPORT std::shared_ptr< GameWorld > _GetWorldForJoinTarget(const std::string &options)
This is called to determine the GameWorld a player should be added to. Return null to disallow joinin...
DLLEXPORT std::shared_ptr< ConnectedPlayer > GetPlayerForConnection(Connection &connection)
Gets corresponding player from a connection.
#define LOG_WARNING(x)
Definition: Define.h:82
std::shared_ptr< CommandHandler > _CommandHandler
The object used to handle all player submitted commands.
Empty response, used for keeping alive/nothing.
DLLEXPORT std::string GenerateFormatedAddressString() const
Returns a nicely formated address string for this connection.
DLLEXPORT void RespondToServerStatusRequest(std::shared_ptr< NetworkRequest > request, Connection &connectiontouse)
Sends a response to a NETWORKREQUESTTYPE_SERVERSTATUS.
DLLEXPORT bool _HandleDefaultRequest(const std::shared_ptr< NetworkRequest > &request, Connection &connectiontosendresult)
Utility function for subclasses to call for default handling.
DLLEXPORT void _HandleServerJoinRequest(std::shared_ptr< NetworkRequest > request, Connection &connection)
Used to handle server join request packets.
The client has made a request with invalid or unsupported options.

◆ HandleResponseOnlyPacket()

DLLEXPORT void NetworkServerInterface::HandleResponseOnlyPacket ( const std::shared_ptr< NetworkResponse > &  message,
Connection connection 
)
overridevirtual

Called by ConnectionInfo when it receives a response without a matching request object.

This is called when the host on the connection sends a response without a matching request. Usually the other program instance wants us to do something without expecting a response, for example they could want us to add a new message to our inbox without expecting a response (other than an ack which is automatically sent) from us. The function can optionally ignore keepalive acks (to reduce spam between clients) by setting dontmarkasreceived as true. This function shouldn't throw any exceptions.

Implements Leviathan::NetworkInterface.

Definition at line 144 of file NetworkServerInterface.cpp.

146 {
147  LEVIATHAN_ASSERT(message, "message is null");
148 
149  if(_HandleDefaultResponseOnly(message, connection))
150  return;
151 
152  switch(message->GetType()) {
154  // Notify the matching player object about a heartbeat //
155  auto ply = GetPlayerForConnection(connection);
156 
157  if(!ply) {
158 
159  Logger::Get()->Warning("NetworkServerInterface: received a heartbeat packet "
160  "from a non-existing player");
161  return;
162  }
163 
164  ply->HeartbeatReceived();
165 
166  // Avoid spamming packets back //
167  // dontmarkasreceived = true;
168 
169  return;
170  }
172  auto data = static_cast<ResponseEntityUpdate*>(message.get());
173 
174  auto world = _GetWorldForEntityMessage(data->WorldID);
175 
176  // TODO: this needs to be queued if we haven't received the world yet
177  if(!world) {
178  LOG_WARNING("NetworkServerInterface: no world found for EntityUpdate");
179  return;
180  }
181 
182  world->HandleEntityPacket(std::move(*data), connection);
183  return;
184  }
185  default: break;
186  }
187 
188  if(_CustomHandleResponseOnlyPacket(message, connection))
189  return;
190 
191  LOG_ERROR(
192  "NetworkServerInterface: failed to handle response of type: " + message->GetTypeStr());
193 }
#define LOG_ERROR(x)
Definition: Define.h:83
DLLEXPORT std::shared_ptr< ConnectedPlayer > GetPlayerForConnection(Connection &connection)
Gets corresponding player from a connection.
#define LOG_WARNING(x)
Definition: Define.h:82
DLLEXPORT bool _HandleDefaultResponseOnly(const std::shared_ptr< NetworkResponse > &message, Connection &connection)
Utility function for subclasses to call for default handling of non-request responses.
DLLEXPORT void Warning(const std::string &data) override
Definition: Logger.cpp:190
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106
virtual DLLEXPORT GameWorld * _GetWorldForEntityMessage(int32_t worldid)
This needs to lookup a GameWorld for an entity update message by id.
virtual bool _CustomHandleResponseOnlyPacket(const std::shared_ptr< NetworkResponse > &message, Connection &connection)

◆ PlayerPotentiallyKicked()

DLLEXPORT bool NetworkServerInterface::PlayerPotentiallyKicked ( ConnectedPlayer player)
protectedvirtual

Definition at line 346 of file NetworkServerInterface.cpp.

347 {
348  return true;
349 }

◆ PlayerPreconnect()

DLLEXPORT void NetworkServerInterface::PlayerPreconnect ( Connection connection,
std::shared_ptr< NetworkRequest joinrequest 
)
protectedvirtual

Called when a player is about to connect.

Definition at line 357 of file NetworkServerInterface.cpp.

359 {}

◆ RegisterCustomCommandHandlers()

DLLEXPORT void NetworkServerInterface::RegisterCustomCommandHandlers ( CommandHandler addhere)
protectedvirtual

Called when the application should register custom command handling providers.

Note
If you actually want to use this call to this should be added to your subclass constructor

Definition at line 374 of file NetworkServerInterface.cpp.

375 {}

◆ RespondToServerStatusRequest()

DLLEXPORT void NetworkServerInterface::RespondToServerStatusRequest ( std::shared_ptr< NetworkRequest request,
Connection connectiontouse 
)

Sends a response to a NETWORKREQUESTTYPE_SERVERSTATUS.

Definition at line 234 of file NetworkServerInterface.cpp.

236 {
237  // Gather info for a response //
238  ResponseServerStatus response(request->GetMessageNumber(), ServerName, AllowJoin,
239  JoinRestrict, ServerStatus, static_cast<int32_t>(ServerPlayers.size()), MaxPlayers,
240  static_cast<int32_t>(ActiveBots.size()), ExtraServerFlags);
241 
242  // Send it //
243  connectiontouse.SendPacketToConnection(response);
244 }
int ExtraServerFlags
This can contain anything the specific game wants.
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.
std::vector< int > ActiveBots
Currently active bots.
std::string ServerName
Name displayed in the server list.
SERVER_JOIN_RESTRICT JoinRestrict
Type of join restriction, defaults to NETWORKRESPONSE_SERVERJOINRESTRICT_NONE.
int MaxPlayers
Maximum allowed player count.

◆ SendToAllButOnePlayer()

DLLEXPORT void NetworkServerInterface::SendToAllButOnePlayer ( const std::shared_ptr< NetworkResponse > &  response,
Connection skipme,
RECEIVE_GUARANTEE  guarantee 
)

Sends a response packet to all players except for the player(s) whose connection matches skipme.

Definition at line 438 of file NetworkServerInterface.cpp.

441 {
442  // Loop the players and send to their connections //
443  for(auto iter = ServerPlayers.begin(); iter != ServerPlayers.end(); ++iter) {
444 
445  Connection* curconnection = (*iter)->GetConnection().get();
446 
447  if(curconnection != skipme) {
448 
449  curconnection->SendPacketToConnection(response, guarantee);
450  }
451  }
452 }
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.
Class that handles a single connection to another instance.
Definition: Connection.h:105

◆ SendToAllPlayers()

DLLEXPORT void NetworkServerInterface::SendToAllPlayers ( const std::shared_ptr< NetworkResponse > &  response,
RECEIVE_GUARANTEE  guarantee 
)

Sends a response packet to all of the players.

Definition at line 454 of file NetworkServerInterface.cpp.

456 {
457  // Loop the players and send to their connections //
458  for(auto iter = ServerPlayers.begin(); iter != ServerPlayers.end(); ++iter) {
459 
460  (*iter)->GetConnection()->SendPacketToConnection(response, guarantee);
461  }
462 }
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.

◆ SetServerAllowPlayers()

DLLEXPORT void NetworkServerInterface::SetServerAllowPlayers ( bool  allowingplayers)

Sets whether the server allows new players.

Definition at line 251 of file NetworkServerInterface.cpp.

252 {
253  AllowJoin = allowingplayers;
254 }

◆ SetServerStatus()

DLLEXPORT void NetworkServerInterface::SetServerStatus ( SERVER_STATUS  newstatus)

Sets the status of the server to newstatus.

Definition at line 246 of file NetworkServerInterface.cpp.

247 {
248  ServerStatus = newstatus;
249 }

◆ TickIt()

DLLEXPORT void NetworkServerInterface::TickIt ( )
overridevirtual

Updates status of the status of the server's clients.

Note
Should be called by NetworkInterface::TickIt
Todo:
Inactive players should be kicked to make DOS:in harder (even shorter limit should be for players that are not currently in any GameWorld)

Implements Leviathan::NetworkInterface.

Definition at line 413 of file NetworkServerInterface.cpp.

414 {
415  // Check for closed connections //
416  auto end = ServerPlayers.end();
417  for(auto iter = ServerPlayers.begin(); iter != end;) {
418 
419  if((*iter)->IsConnectionClosed()) {
420 
421  // The player has disconnected //
423 
424  iter = ServerPlayers.erase(iter);
425  // The end iterator is now also invalid //
426  end = ServerPlayers.end();
427  continue;
428  }
429 
430  (*iter)->UpdateHeartbeats();
431  ++iter;
432  }
433 
434  // Update the command handling //
435  _CommandHandler->UpdateStatus();
436 }
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.
void _OnReportCloseConnection(std::shared_ptr< ConnectedPlayer > plyptr)
std::shared_ptr< CommandHandler > _CommandHandler
The object used to handle all player submitted commands.

◆ VerifyWorldIsSyncedWithPlayers()

DLLEXPORT void NetworkServerInterface::VerifyWorldIsSyncedWithPlayers ( std::shared_ptr< GameWorld world)
virtual

Verifies that all current players are receiving world updates.

Note
Prior to calling this (if your players will move) you should bind positionable objects to the players for them to receive updates based on their location

Definition at line 464 of file NetworkServerInterface.cpp.

466 {
467  // We can safely add all players as they will only be added if they aren't there already //
468  for(auto iter = ServerPlayers.begin(); iter != ServerPlayers.end(); ++iter)
469  world->SetPlayerReceiveWorld(*iter);
470 }
std::vector< std::shared_ptr< ConnectedPlayer > > ServerPlayers
Holds the list of currently connected players.

Member Data Documentation

◆ _CommandHandler

std::shared_ptr<CommandHandler> Leviathan::NetworkServerInterface::_CommandHandler = nullptr
protected

The object used to handle all player submitted commands.

Definition at line 181 of file NetworkServerInterface.h.

◆ ActiveBots

std::vector<int> Leviathan::NetworkServerInterface::ActiveBots
protected

Currently active bots.

Definition at line 158 of file NetworkServerInterface.h.

◆ AllowJoin

bool Leviathan::NetworkServerInterface::AllowJoin = false
protected

Controls whether players can join Used to prevent players joining during start up

Definition at line 165 of file NetworkServerInterface.h.

◆ CurrentPlayerID

int Leviathan::NetworkServerInterface::CurrentPlayerID = 1000
protected

Player ID counter for assigning unique ids for all players.

Definition at line 178 of file NetworkServerInterface.h.

◆ ExtraServerFlags

int Leviathan::NetworkServerInterface::ExtraServerFlags = 0
protected

This can contain anything the specific game wants.

Definition at line 175 of file NetworkServerInterface.h.

◆ JoinRestrict

SERVER_JOIN_RESTRICT Leviathan::NetworkServerInterface::JoinRestrict = SERVER_JOIN_RESTRICT::Localhost
protected

Type of join restriction, defaults to NETWORKRESPONSE_SERVERJOINRESTRICT_NONE.

Definition at line 168 of file NetworkServerInterface.h.

◆ MaxPlayers

int Leviathan::NetworkServerInterface::MaxPlayers = 20
protected

Maximum allowed player count.

Definition at line 155 of file NetworkServerInterface.h.

◆ ServerName

std::string Leviathan::NetworkServerInterface::ServerName = "Default Name"
protected

Name displayed in the server list.

Definition at line 161 of file NetworkServerInterface.h.

◆ ServerPlayers

std::vector<std::shared_ptr<ConnectedPlayer> > Leviathan::NetworkServerInterface::ServerPlayers
protected

Holds the list of currently connected players.

Definition at line 150 of file NetworkServerInterface.h.

◆ ServerPlayersConnections

std::vector<std::shared_ptr<Connection> > Leviathan::NetworkServerInterface::ServerPlayersConnections
protected

All the connections used in ServerPlayers.

Definition at line 152 of file NetworkServerInterface.h.

◆ ServerStatus

SERVER_STATUS Leviathan::NetworkServerInterface::ServerStatus = SERVER_STATUS::Starting
protected

Server status, initially NETWORKRESPONSE_SERVERSTATUS_STARTING and should be set by the application when appropriate

Definition at line 172 of file NetworkServerInterface.h.


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