Game Development Reference
In-Depth Information
Listing 9-24. New Global Variables for the Client
var Socket = null;
var GameTimer = null;
The first is our WebSocket and the second will be used to stop the game loop if the WebSocket connection
is aborted. When the page loads, we'll ask the player for a handle and then connect to the WebSocket
server. So, in our window-load event handler, we add the code as shown in Listing 9-25.
Listing 9-25. Modification of Window Load Event Handler in the Client
...
GraphicsContext = BumperCanvas.getContext("2d");
var Name = prompt("What is your username?", "Anonymous");
GraphicsContext.textAlign = "center";
GraphicsContext.fillText("Connecting...", GP.GameWidth / 2, GP.GameHeight / 2);
try
{
if (typeof MozWebSocket !== "undefined")
Socket = new MozWebSocket("ws://SERVERIP:9001");
else if (typeof WebSocket !== "undefined")
Socket = new WebSocket("ws://SERVERIP:9001");
else
{
Socket = null;
alert("Your browser does not support websockets. We recommend that you use
an up-to-date version of Google Chrome or Mozilla Firefox.");
return false;
}
}
catch (E) { Socket = null; return false; }
At the time of this writing, Firefox calls its WebSocket type MozWebSocket . That may change in the future.
For the time being, the code in Listing 9-25 is compatible with both Firefox and Chrome. Of course,
SERVERIP should be replaced by the IP address of the server running server.js, be it 127.0.0.1 or the IP
address of a remote server.
Next, in Listing 9-26, we listen for events raised by the WebSocket, and then we will be done with the
window-load event handler.
Listing 9-26. WebSocket Event Handlers
Socket.onerror = function(E) { alert("WebSocket error: " + JSON.stringify(E)); };
Socket.onclose = function (E)
{
// Shut down the game loop.
if (GameTimer) clearInterval(GameTimer);
GameTimer = null;
};
Socket.onopen = function()
 
Search WWH ::




Custom Search