Game Development Reference
In-Depth Information
Note The WebSocket server add-on modules are sure to change in the future,
especially once the WebSocket standard is finalized, but the code we write here will be
largely agnostic of the module used. It should be easily adapted to any other module
fulfilling the same purpose.
Our server.js will need to
establish a WebSocket server
run a game loop, maintaining the authoritative state of all the players' cars
receive and act on player input
periodically send out game state to all the players
We'll begin by importing the modules that we need (similar to using #include in C), as shown in Listing 9-14.
Listing 9-14. Importing node.js Modules
var System = require("util");
var HTTP = require("http");
var WebSocketServer = require("/path/to/websocket").server;
var Game = require("/path/to/game");
The sys and http modules come with node.js, but the websocket module is what we downloaded a moment
ago, and the game module is actually just our game.js. You can either put these files (the websocket module
and game.js) where node.js knows to look for them or you can specify the full paths explicitly (if game.js is
located at /home/user123/bumper/game.js , you will do require("/home/user123/bumper/game") ). The
exports code we added at the end of game.js is important here: only those variables exported by game.js will
be accessible to server.js. Now, as shown in Listing 9-15, some global variables that we'll use throughout
server.js.
Listing 9-15. Global Variables for the Server
var Frame = 0;
var FramesPerGameStateTransmission = 3;
var MaxConnections = 10;
var Connections = {};
Frame will count game frames, though we won't do any intricate timing in this example game.
FramesPerGameStateTransmission will control how often game state is broadcasted to players; in this case
it's after every three game frames. In game.js, we specified GameFrameTime to be 20 milliseconds, so
updates will be sent out about every 60 ms, or approximately 17 times per second. MaxConnections will
limit the number of connections we allow on our server. Connections will contain data about the players,
including their car state but also stuff about the WebSocket connection: IP address, and so forth.
At this point we can immediately accomplish our first goal. It is very simple to set up a WebSocket server
in the environment we've chosen (see Listing 9-16). A WebSocket server piggybacks on a regular old
HTTP server, and node.js can create an HTTP server for us in one line.
 
Search WWH ::




Custom Search