Game Development Reference
In-Depth Information
Notice that we again augmented, for the final time, the list of data stored per car. We're now keeping track
of the user's handle (username) and it will be displayed on the cars once we revisit the game client.
Caution Always perform strict data validation on any input received from users! It is
very simple for a user to change the game client and send messages out of order or
send messages that the server does not understand. If you are not careful, these can
crash your server or worse.
Of course, the method SendGameState , called after the handshake, is all-important. It will broadcast all of
the game data to all of the players several times per second. In a more complicated game, especially one
with many users, this will be something that you want to optimize for speed and bandwidth efficiency. In
our case, these aren't important concerns. We proceed pretty naively, then in Listing 9-22.
Listing 9-22. SendGameState Method
function SendGameState()
{
var CarData = [];
var Indices = {};
// Collect all the car objects to be sent out to the clients
for (var ID in Connections)
{
// Some users may not have Car objects yet (if they haven't done the handshake)
var C = Connections[ID];
if (!C.Car) continue;
CarData.push(C.Car);
// Each user will be sent the same list of car objects, but needs to be able to
pick
// out his car from the pack. Here we take note of the index that belongs to
him.
Indices[ID] = CarData.length - 1;
}
// Go through all of the connections and send them personalized messages. Each user
gets
// the list of all the cars, but also the index of his car in that list.
for (var ID in Connections)
Connections[ID].sendUTF(JSON.stringify({ MyIndex: Indices[ID], Cars: CarData
}));
}
The message we send out is a JSON-encoded string made from the object { MyIndex: ..., Cars: ... } .
Each user will get a personalized message like this, with all the car information (including his own car), as
well as the index of his car in the group. The way we send data is very simple: each element of
Connections has the method sendUTF() (part of WebSocket-Node's type, WebSocketConnection ) that
accepts a string as input.
 
Search WWH ::




Custom Search