Game Development Reference
In-Depth Information
Size++;
return Size;
}
The event handler for the player disconnecting is very simple. Notice that in Listing 9-18 we directed that
event to a function called HandleClientClosure (see Listing 9-19).
Listing 9-19. HandleClientClosure method
function HandleClientClosure(ID)
{
if (ID in Connections)
{
System.log("Disconnect from " + Connections[ID].IP);
delete Connections[ID];
}
}
Likewise, when we receive data from a player, we process it in HandleClientMessage . Let's outline the
behavior of that function in Listing 9-20.
Listing 9-20. HandleClientMessage outline
function HandleClientMessage(ID, Message)
{
// Check that we know this client ID and that the message is in a format we expect.
// Handle the different types of messages we expect:
// - Handshake message where the player tells us his name
// --> Create his car object and send everybody the good news.
// - Key was pressed.
// --> Update the player's personal KeyPressed bitfield.
// - Key was released.
// --> Ditto.
}
It is completely up to us to choose a message format. Using JavaScript, a natural choice is JSON that is
nothing more than a standardized way of encoding JavaScript variable data. We could easily make our
messages shorter or more obscure, but there is no benefit to that in the present case. JSON support is
ubiquitous, with all modern browsers (and node.js) supporting the routines JSON.stringify() for encoding
and JSON.parse() for decoding. Therefore, we will choose our server-bound messages to be JSON-
encoded JavaScript objects in the format { Type: ..., Data: ... } . The three types of messages will be
"HI" for handshake, "U" for key up, and "D" for key down. Now, in Listing 9-21, let's fill out
HandleClientMessage .
Listing 9-21. HandleClientMessage Method
function HandleClientMessage(ID, Message)
{
// Check that we know this client ID and that the message is in a format we expect.
if (!(ID in Connections)) return;
 
Search WWH ::




Custom Search