Game Development Reference
In-Depth Information
Note
some trivial methods have been omitted.
Listening for a connection over TCP must be decoupled from the WebSocket server itself. Each instance of
WebSocketServer is responsible for only one client. This separation keeps the code and resource allocation simple.
A higher-level system should manage multiple connection requests and multiple live WebSocket connections.
My WebSocket server has a single Update method. This method pumps the connection. It is responsible for
sending any pending messages, receiving any new messages (ultimately moving them to the message buffer), and
updating status flags (connection opened, connection closed, connection error).
Complete incoming messages are stored in their own buffer. When the engine system is ready to process
incoming messages, a call to ProcessMessages is made and a delegate function is passed in. The WebSocketServer
will iterate over all messages in the buffer and call this delegate for each one. When the engine is done with the
messages, it must clear them by calling ClearMessages .
I started with the explicit goal of supporting multiple connected clients. I've discussed the importance of
decoupling the code that waits for a connection over TCP from the code that manages a WebSocket connection.
Because of that decoupling, supporting multiple connections is practically free.
Command Processing
Support for commands is added by implementing the commander interface, as shown in Listing 10-9.
Listing 10-9. Implementing the Commander Interface
class doCommandCenterCommanderInterface {
public:
virtual const char* CommanderName() const = 0;
virtual bool CanProcessCommand(const doCommandCenterCommandPacket* packet) const = 0;
virtual void ProcessCommand(doCommandCenterConnection* connection, const
doCommandCenterCommandPacket* packet) = 0;
};
A commander can process one or many commands ( CanProcessCommand ). Each commander is registered
with the central command center, which routes messages from connected clients to the appropriate commander.
doCommandCenterCommandPacket just contains a parsed JSON object, and doCommandCenterConnection has the
WebSocket connection and various buffers in it.
Support for reports is added by implementing the reporter interface, as shown in Listing 10-10.
Listing 10-10. Implementing the Reporter Interface
class doCommandCenterReporterInterface {
public:
virtual const char* ReporterName() const = 0;
// Update internal state
virtual void Refresh() = 0;
// Report state to all subscribed connections
virtual void Report() = 0;
};
Each reporter is responsible for generating a single type of report. Similar to commanders, reporters are
registered in the central command center.
Client commands to subscribe and unsubscribe are processed by a commander, like all other commands.
 
 
Search WWH ::




Custom Search