Game Development Reference
In-Depth Information
do
{
Connection.ID = Math.floor(Math.random() * 100000)
} while (Connection.ID in Connections);
Connections[Connection.ID] = Connection;
Connection.on("message",
function(Message)
{
// All of our messages will be transmitted as unicode text.
if (Message.type == "utf8")
HandleClientMessage(Connection.ID, Message.utf8Data);
}
);
Connection.on("close",
function()
{
HandleClientClosure(Connection.ID);
}
);
System.log("Logged in " + Connection.IP + "; currently " +
ObjectSize(Connections) + " users.");
}
);
Note that the Server object (our WebSocket server) registers event listeners using on() , in the same way
that addEventListener is used for DOM objects in the browser. The method is relatively straightforward. In
summary, we do the following:
Check that we're not running afoul of the connection limit (this connection limit is not needed, but
it is here to illustrate rejecting a connection).
Call accept (as opposed to reject ) on the Request object.
Store the client's IP address and assign a unique ID number to the client for internal use.
Attach event listeners to this player's Connection object ( close is raised when the connection is
closed and message is raised whenever that player sends us data).
You may have noticed ObjectSize being applied to Connections . We can't get the size of Connections
using Connections.length because it's an object rather than an array. So, we implement this simple
counting routine ourselves, as shown in Listing 9-18.
Listing 9-18. Generic Method to Count Size of JavaScript Objects
function ObjectSize(Obj)
{
var Size = 0;
for (var Key in Obj)
if (Obj.hasOwnProperty(Key))
 
Search WWH ::




Custom Search